StockLedgerRpt Class showing null pointer exception. This class displays a list in spinner view to select a stock item.
package com.manacle.umma.activity;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.manacle.umma.java.Constants;
import com.manacle.umma.java.DatabaseHelper;
import com.manacle.umma.java.Header;
import com.manacle.umma.java.Validation;
public class StockLedgerRep extends ListActivity {
Button srch_btn;
TextView stckldgr_header, stckldgr_cntr, frm_date, to_date,
stck_item;
EditText to_dt_edit, frm_dt_edit;
Spinner add_stcitm_spin;
RelativeLayout stckldgr_relative;
LinearLayout stckldgr_linearLayout;
HeaderDb headerDb;
ListAdapter adapter;
Header headerClass;
HashMap<String, String> map, categoryMap, unitMap;
String value, stockId, voucherId, code;
String stockItemsname[] = null;
String batchId = null;
DatabaseHelper databaseHelper;
Map stockItemMap;
SharedPreferences preferences;
String itemname;
String firstSelection;
private TextToSpeech tts;
String batchIDD;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stck_ldgr_rpt);
final HeaderDb db = new HeaderDb(getApplicationContext());
headerDb = new HeaderDb(getApplicationContext());
stckldgr_relative = (RelativeLayout) findViewById(R.id.stckldgr_relative_layout);
stckldgr_linearLayout = (LinearLayout) findViewById(R.id.stckldgr_linear_layout);
stckldgr_header = (TextView) findViewById(R.id.stckldgr_header);
stckldgr_cntr = (TextView) findViewById(R.id.stckldgr_txt);
frm_date = (TextView) findViewById(R.id.stckldgr_frmdate_txt);
to_date= (TextView) findViewById(R.id.stckldgr_todate_txt);
stck_item=(TextView) findViewById(R.id.stckldgr_stockItem_txt);
add_stcitm_spin=(Spinner) findViewById(R.id.stckldgr_stock_item_spinner);
frm_dt_edit = (EditText) findViewById(R.id.stckldgr_frmdate_edit);
to_dt_edit = (EditText) findViewById(R.id.stckldgr_todate_edit);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
frm_dt_edit.setText(dateFormat.format(date));
frm_dt_edit.setFocusable(false);
to_dt_edit.setText(dateFormat.format(date));
to_dt_edit.setFocusable(false);
String dat = preferences.getString("STOCK_CODE", "");
if (!dat.equalsIgnoreCase("")) {
// Toast.makeText(getApplicationContext(), "Selected date="+dat,
// Toast.LENGTH_LONG).show();
stckldgr_cntr.setText(dat);
}
final OnDateSetListener odsl = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
String date_format = Validation.dateFormat(month, day, year);
frm_dt_edit.setText(date_format);
to_dt_edit.setText(date_format);
}
};
frm_dt_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
DatePickerDialog datePickDiag = new DatePickerDialog(
StockLedgerRep.this, odsl, cal.get(Calendar.YEAR), cal
.get(Calendar.MONTH), cal
.get(Calendar.DAY_OF_MONTH));
datePickDiag.show();
}
});
to_dt_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
DatePickerDialog datePickDiag = new DatePickerDialog(
StockLedgerRep.this, odsl, cal.get(Calendar.YEAR), cal
.get(Calendar.MONTH), cal
.get(Calendar.DAY_OF_MONTH));
datePickDiag.show();
}
});
com.manacle.umma.java.SpinnerAdapter adapter1 = new com.manacle.umma.java.SpinnerAdapter(
this, android.R.layout.simple_spinner_item, getStockItem());
add_stcitm_spin.setAdapter(adapter1);
add_stcitm_spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Object item = arg0.getItemAtPosition(arg2);
if (item.equals("")) {
} else {
firstSelection = add_stcitm_spin.getSelectedItem()
.toString();
// tToast(""+firstSelection);
if (firstSelection.equals("All")) {
if (headerDb.getVouDateTransIdfromVouTableforAllItem(value, batchId).size() > 0) {
//showAllName_Id();
} else {
// tToast("No Record, Please add new Record.");
//showAllName_Id();
}
} else {
List stockItemList = headerDb
.getAllIRMStockItem(headerDb
.getAllIRMStockcategoryID());
Map mapItem = (Map) stockItemList.get(arg2 - 1);
code = (String) mapItem.get(add_stcitm_spin
.getSelectedItem().toString());
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); }
private void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.show();
}
public String[] getStockItem() {
String arr_name[] = null;
List listCategoryId = headerDb.getAllIRMStockcategoryID();
List stockList = headerDb.getAllIRMStockItem(listCategoryId);
Iterator memberItemsItr = headerDb.getAllIRMStockItem(listCategoryId)
.iterator();
int i = 0;
arr_name = new String[stockList.size() + 1];
arr_name[0] = "All";
i++;
// tToast("ARRSIZE="+listCategoryId.size());
while (memberItemsItr.hasNext()) {
stockItemMap = (Map) memberItemsItr.next();
Iterator<?> iter = stockItemMap.entrySet().iterator();
// String arr_code[]=new String[memberItemsMap.size()+1];
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
// tToast(mEntry.getKey() + " : " + mEntry.getValue());
String stockName = (String) mEntry.getKey();
String stockCode = (String) mEntry.getValue();
arr_name[i] = stockName;
i++;
}
}
return arr_name;
}
public void showAllName_Id() {
adapter = new SimpleAdapter(this, headerDb.getVouDateTransIdfromVouTableforAllItem(value, batchId),
R.layout.stock_list_item, new String[] {
Constants.Bat_Acc_Voch_VOUCHER_DATE,
Constants.Bat_Acc_Voch_Trans_Id }, new int[] {
R.id.stock_list_code, R.id.stock_list_name });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// lv.setBackgroundColor(Integer.parseInt(headerDb.getBgColor("KD125"),
// 16)+0xFF000000);
// lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
try {
// lv.setSelector(R.drawable.sel);
} catch (Exception e) {
// TODO: handle exception
tToast("Error" + e);
}
// lv.setSelector(Color.RED);
lv.setOnTouchListener(new ListView.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
// v.setBackgroundResource(R.drawable.sel);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
// v.setBackgroundResource(R.drawable.sel);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view
.findViewById(R.id.stock_list_code)).getText()
.toString();
voucherId = ((TextView) view.findViewById(R.id.stock_list_name))
.getText().toString();
String Vid[] = voucherId.split("-");
String vid = Vid[1];
String mobtrans = Vid[0];
// tToast("Voucher Id="+vid);
// tToast("Selected Value="+name+""+code);
Intent in = new Intent(getApplicationContext(),
IRM_add_preview.class);
in.putExtra("VOU_ID", vid);
in.putExtra("VALUE", value);
in.putExtra("MOBTRANS", mobtrans);
startActivity(in);
}
});
}
}
stck_ldgr Xml this xml shows three things one is the spinner stock items column and the other two are select dates. I am unable to get the error. pls help. even added in androidmanifest.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:id="#+id/stckldgr_relative_layout"
>
<TextView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="10dp"
/>
<TextView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/imageView1"
android:orientation="vertical"
android:id="#+id/stckldgr_linear_layout"
>
<!-- -->
<ScrollView
android:id="#+id/scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingTop="6dip"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Stock Ledger Report"
android:textStyle="bold"
android:gravity="center"
android:id="#+id/stckldgr_header"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#ff106510"
android:layout_marginLeft="6dip"
android:layout_marginRight="6dip"
android:layout_marginTop="6dip"
android:layout_marginBottom="12dip" />
<LinearLayout
android:id="#+id/linearLayout_login_4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:id="#+id/stckldgr_txt"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Stock Center Code-Name"
android:gravity="center"
/>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:text="Stock Item"
android:height="40dp"
android:width="150dp"
android:layout_marginTop="10dip"
android:textStyle="bold"
android:id="#+id/stckldgr_stockItem_txt"
android:layout_gravity="center_horizontal|bottom"
></TextView>
<Spinner
android:id="#+id/stckldgr_stock_item_spinner"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginRight="6dip"
android:saveEnabled="true" >
</Spinner>
</TableRow>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
>
<TextView
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginTop="10dip"
android:text="From Date"
android:textStyle="bold"
android:id="#+id/stckldgr_frmdate_txt"
/>
<EditText
android:id="#+id/stckldgr_frmdate_edit"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="0dip"
android:layout_marginRight="10dip"
android:editable="false"
>
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
>
<TextView
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginTop="10dip"
android:text="To Date"
android:textStyle="bold"
android:id="#+id/stckldgr_todate_txt"
/>
<EditText
android:id="#+id/stckldgr_todate_edit"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="0dip"
android:layout_marginRight="10dip"
android:editable="false"
>
<requestFocus />
</EditText>
</TableRow>
</TableLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:layout_weight="1"
android:divider="#color/divider"
android:listSelector="#369659"
android:cacheColorHint="#369659"
android:dividerHeight="2px"
android:choiceMode="singleChoice"
android:gravity="center" >
</ListView>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
</RelativeLayout>
Logcat
10-10 10:44:55.832: D/AndroidRuntime(2639): Shutting down VM
10-10 10:44:55.865: W/dalvikvm(2639): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-10 10:44:56.023: E/AndroidRuntime(2639): FATAL EXCEPTION: main
10-10 10:44:56.023: E/AndroidRuntime(2639): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.manacle.umma.activity/com.manacle.umma.activity.StockLedgerRep}: java.lang.NullPointerException
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.os.Handler.dispatchMessage(Handler.java:99)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.os.Looper.loop(Looper.java:137)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-10 10:44:56.023: E/AndroidRuntime(2639): at java.lang.reflect.Method.invokeNative(Native Method)
10-10 10:44:56.023: E/AndroidRuntime(2639): at java.lang.reflect.Method.invoke(Method.java:511)
10-10 10:44:56.023: E/AndroidRuntime(2639): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-10 10:44:56.023: E/AndroidRuntime(2639): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-10 10:44:56.023: E/AndroidRuntime(2639): at dalvik.system.NativeStart.main(Native Method)
10-10 10:44:56.023: E/AndroidRuntime(2639): Caused by: java.lang.NullPointerException
10-10 10:44:56.023: E/AndroidRuntime(2639): at com.manacle.umma.activity.StockLedgerRep.onCreate(StockLedgerRep.java:96)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.Activity.performCreate(Activity.java:5104)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-10 10:44:56.023: E/AndroidRuntime(2639): ... 11 more
Your preferences object is null.
You need to initialise it before you use it. Something like this:
preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dat = preferences.getString("STOCK_CODE", "");
Because you didn't initialize preferences. Here is the problem:
String dat = preferences.getString("STOCK_CODE", "");
If you use Eclipse or any other IDE, you should double-click on the error line so it will get you right on the source of the exception...
10-10 10:44:56.023: E/AndroidRuntime(2639): at com.manacle.umma.activity.StockLedgerRep.onCreate(StockLedgerRep.java:96)
Should be on the preferences thing like other users suggest...
Can you write this code before line 96.
preferences= getApplicationContext.getSharedPreferences("blablabla", Context.MODE_PRIVATE);
Related
I am trying to make an app to list the schools in my area and I made a table in a database to contain these schools. I made a list view with clickable items to list the names of the schools and when I click on the item to move to another activity and send the clicked school name in order to list more information about the school, the app stops working. The following is one of the activities that contains this list view:
package com.example.welcome.madrasti;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class ListOfSchoolsPublic extends AppCompatActivity {
Intent redirect;
Intent item;
ListView list;
ArrayList<String> _sa;
DBAdapter db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_schools_public);
openDB();
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
Cursor cursor = db.getAllRows();
_sa= new ArrayList<String>();
//cursor.moveToFirst();
Log.d("CURSORCOUNT","Number of rows in the Cursor is = " + String.valueOf(cursor.getCount()));
while(cursor.moveToNext()) {
if(cursor.getString(DBAdapter.COL_SChOOL_TYPE_TABLE_2).equals("حكومية"))
_sa.add(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,_sa);
list.setAdapter(new TempLyaout(ListOfSchoolsPublic.this,_sa));
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
String selectedItem = (String) arg0.getItemAtPosition(position);
itemInfo(selectedItem);
}
});
}
///////////////////////////////////////////////////////////////
public void itemInfo(String selectedItem){
item = new Intent(getApplicationContext(), NewSchool.class);
item.putExtra("schoolName",selectedItem);
startActivity(item);
}
///////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////
private void openDB() {
db = new DBAdapter(ListOfSchoolsPublic.this);
db.open();
} // end openDB method
//////////////////////////////////////////////////////////////
private void closeDB() {
db.close();
} // end closeDB method
}
The following is the activity that each list item should move to:
package com.example.welcome.madrasti;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class NewSchool extends AppCompatActivity {
Intent intent;
Intent nextPage;
Button next;
DBAdapter db;
TextView t1;
TextView t2;
TextView t3;
TextView t4;
TextView t5;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_school);
t1=(TextView)findViewById(R.id.textView9) ;
t2=(TextView)findViewById(R.id.textView11) ;
t3=(TextView)findViewById(R.id.textView12) ;
t4=(TextView)findViewById(R.id.textView17) ;
t5=(TextView)findViewById(R.id.textView18) ;
next = (Button) findViewById(R.id.button);
intent = getIntent();
name = intent.getStringExtra("schoolName");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goNext();
}
});
Cursor cursor = db.getAllRows();
while(cursor.moveToNext()) {
if(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2).equals(name)){
t1.setText(DBAdapter.COL_SCHOOLNAME_TABLE_2);
t2.setText(DBAdapter.COL_FOUNDATION_DATE_TABLE_2);
t3.setText(DBAdapter.COL_BUY_BOOKS_TABLE_2);
t4.setText(DBAdapter.COL_HEALTH_TABLE_2);
t5.setText(DBAdapter.COL_LOCATION_TABLE_2);
}
}
cursor.close();
}
public void goNext(){
nextPage = new Intent(getApplicationContext(),NewShoolAct2.class);
nextPage.putExtra("schoolName",name);
startActivity(nextPage);
}
///////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////
private void openDB() {
db = new DBAdapter(NewSchool.this);
db.open();
} // end openDB method
//////////////////////////////////////////////////////////////
private void closeDB() {
db.close();
} // end closeDB method
}
The following is the XML of the previous activity:
<?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"
android:background="#drawable/login_background"
tools:context="com.example.welcome.madrasti.NewSchool">
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_x="244dp"
android:layout_y="54dp"
android:text="إسم المدرسة:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="dp"
tools:layout_editor_absoluteY="10dp" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="240dp"
android:layout_y="127dp"
android:text="تاريخ التأسيس:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="297dp"
tools:layout_editor_absoluteY="144dp" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="231dp"
android:layout_y="185dp"
android:text="كيفية شراء الكتب:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="284dp"
tools:layout_editor_absoluteY="210dp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="215dp"
android:layout_y="265dp"
android:text="وضع المرافق الصحية:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="265dp"
tools:layout_editor_absoluteY="288dp" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="244dp"
android:layout_y="340dp"
android:text="موقع المدرسة:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="300dp"
tools:layout_editor_absoluteY="368dp" />
<Button
android:id="#+id/button"
android:layout_width="98dp"
android:layout_height="34dp"
android:layout_x="133dp"
android:layout_y="434dp"
android:background="#drawable/button"
android:text="التالي"
android:textAlignment="center"
android:textColor="#ffff"
android:textStyle="bold"
tools:layout_editor_absoluteX="45dp"
tools:layout_editor_absoluteY="426dp" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="11dp"
android:layout_y="77dp"
android:text="TextView"
tools:layout_editor_absoluteX="18dp"
tools:layout_editor_absoluteY="59dp" />
<TextView
android:id="#+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="12dp"
android:layout_y="148dp"
android:text="TextView"
tools:layout_editor_absoluteX="12dp"
tools:layout_editor_absoluteY="150dp" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="32345dp"
android:layout_y="32418dp"
android:text="TextView"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="235dp" />
<TextView
android:id="#+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="15dp"
android:layout_y="299dp"
android:text="TextView"
tools:layout_editor_absoluteX="21dp"
tools:layout_editor_absoluteY="37dp" />
<TextView
android:id="#+id/textView18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="16dp"
android:layout_y="372dp"
android:text="TextView"
tools:layout_editor_absoluteX="17dp"
tools:layout_editor_absoluteY="381dp" />
<TextView
android:id="#+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="16dp"
android:layout_y="219dp"
android:text="TextView"
tools:layout_editor_absoluteX="10dp"
tools:layout_editor_absoluteY="215dp" />
</AbsoluteLayout>
</android.support.constraint.ConstraintLayout>
The following is the log cat when the app is crashed:
04-13 17:57:49.245 5828-5828/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
04-13 17:57:49.245 5828-5828/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
04-13 17:57:49.245 5828-5828/? I/art: Late-enabling -Xcheck:jni
04-13 17:57:49.435 5828-5838/? I/art: Debugger is no longer active
04-13 17:57:49.492 5828-5828/? I/InstantRun: starting instant run server: is main process
04-13 17:57:49.602 5828-5843/? W/art: Suspending all threads took: 11.737ms
04-13 17:57:49.605 5828-5843/? I/art: Background sticky concurrent mark sweep GC freed 2038(168KB) AllocSpace objects, 0(0B) LOS objects, 25% free, 832KB/1117KB, paused 13.068ms total 21.305ms
04-13 17:57:49.630 5828-5828/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-13 17:57:49.779 5828-5847/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-13 17:57:49.784 5828-5828/? D/Atlas: Validating map...
04-13 17:57:49.810 5828-5847/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-13 17:57:49.820 5828-5847/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
04-13 17:57:49.848 5828-5847/? I/OpenGLRenderer: Initialized EGL, version 1.4
04-13 17:57:49.878 5828-5847/? D/OpenGLRenderer: Enabling debug mode 0
04-13 17:57:49.896 5828-5847/? W/EGL_emulation: eglSurfaceAttrib not implemented
04-13 17:57:49.896 5828-5847/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe2c15340, error=EGL_SUCCESS
What is the problem please? how to fix it?
Use intents and read basic android first. There are number of options already available for this.
You can Store your string into some other class like this:
Store string:
String selectedItem = (String) arg0.getItemAtPosition(position);
Share.love=selectedItem ;
Get string:
in Your next Activity
Textview textview=(Textview)findviewbyid(R.id.yourname);
textview.setText(Share.love);
Make class
public class Share {
public static String love = "";
}
Try the following example (It uses putExtra() to pass a string to another activity):
Demo15.class:------------
public class Demo15 extends AppCompatActivity {
private Button b;
private EditText edt;
private final String EXTRA_TEXT_ = "extra_text_";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo17);
edt = (EditText) findViewById(R.id.edt);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Demo15.this, Demo16.class);
if (!edt.getText().toString().isEmpty()) {
i.putExtra(EXTRA_TEXT_, edt.getText().toString());
}
startActivity(i);
}
});
}
}
Demo16.class:-------
public class Demo16 extends AppCompatActivity {
private TextView tv;
private final String EXTRA_TEXT_ = "extra_text_";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo18);
tv = (TextView) findViewById(R.id.tv);
if (getIntent() != null) {
if (getIntent().getStringExtra(EXTRA_TEXT_) != null) {
tv.setText(getIntent().getStringExtra(EXTRA_TEXT_));
}
}
}
}
demo17.xml:-------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text to pass"
android:id="#+id/edt"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start the other activity"
android:textAllCaps="false"
android:layout_marginTop="50dp"
android:id="#+id/b"/>
</LinearLayout>
demo18.xml:---------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="####"
android:id="#+id/tv"/>
</android.support.constraint.ConstraintLayout>
Use bundle with intents as android standards.
Example:
Intent intent=new Intent(CurrentActivity.this,NewActivity.class);
intent.putExtra("schoolname","Name of school");
startActivity
I've created a spinner that takes some user-generated strings (in my case classes - the school type) and displays them in a typical spinner way. My problem occurs when trying to select an item from the spinner. I can tap on the spinner and select the class, but the spinner never shows that I have the class selected. Before adding user-generated strings, I had a string-array xml file that worked perfectly.
I've tried adding notifyDataSetChanged() at the end of the onCreate() method, created a spinner layout with a transparent background and black text, and setting an setOnItemSelectedListener(). None of these worked, so I reverted code back to original state.
Screenshot of problem:
addAssignment.java
package com.nbdeg.unityplanner;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nbdeg.unityplanner.data.Assignments;
import com.nbdeg.unityplanner.data.Classes;
import java.util.ArrayList;
public class addAssignment extends AppCompatActivity {
EditText mAssignmentName;
EditText mDueDate;
EditText mExtraInfo;
Spinner mDueClass;
SeekBar mPercentComplete;
int percentComplete = 0;
FirebaseAnalytics mFirebaseAnalytics;
DatabaseReference assignmentDb;
DatabaseReference classDb;
FirebaseUser user;
long assignmentCounter;
ArrayList<String> classList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_assignment);
// Sets title to "Create an assignment"
try {getSupportActionBar().setTitle("Create An Assignment");}
catch (NullPointerException e) {
e.printStackTrace();
}
// Getting number of assignments (serves as assignment ID in database)
Bundle extras = getIntent().getExtras();
assignmentCounter = extras.getLong("counter");
// Finds firebase database
user = FirebaseAuth.getInstance().getCurrentUser();
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
assignmentDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("assignments");
classDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("classes");
// Gets all classes
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i("Info", "Class loaded: " + mClass.getClassName());
classList.add(mClass.getClassName());
}
Log.i("Info", "Classes loaded: " + classList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DB", "Error: " + databaseError.getMessage());
}
});
// Find view by ID calls
mAssignmentName = (EditText) findViewById(R.id.assignment_name);
mDueDate = (EditText) findViewById(R.id.due_date_edittext);
mExtraInfo = (EditText) findViewById(R.id.extra_homework_info);
mDueClass = (Spinner) findViewById(R.id.class_spinner);
mPercentComplete = (SeekBar) findViewById(R.id.percentComplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
// Sets DueDate EditText to open a datepicker when clicked
new EditTextDatePicker(this, R.id.due_date_edittext);
mPercentComplete.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
percentComplete = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
// Adds a SAVE button to the Action Bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save, menu);
return true;
}
// Gets and saves information when SAVE is clicked
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Getting information from views
String dueDate = mDueDate.getText().toString();
String assignmentName = mAssignmentName.getText().toString();
String extraInfo = mExtraInfo.getText().toString();
String dueClass = mDueClass.getItemAtPosition(mDueClass.getSelectedItemPosition()).toString();
mFirebaseAnalytics.logEvent("Assignment Created", null);
Log.i("DB", "Creating assignment named " + assignmentName);
assignmentDb.child(Long.toString(assignmentCounter)).setValue
(new Assignments(assignmentName, dueClass, dueDate, extraInfo, percentComplete));
/*
// Test to make sure info is being collected correctly.
Log.i("Class", dueClass);
Log.i("Due", dueDate);
Log.i("Name", homeworkName);
Log.i("Extra", extraInfo);
*/
// Bring user back to MainActivity
startActivity(new Intent(addAssignment.this, MainActivity.class));
return super.onOptionsItemSelected(item);
}
}
activity_add_assignment.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:id="#+id/activity_add_homework"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.nbdeg.unityplanner.addAssignment">
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="textCapSentences"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/assignment_name"
android:hint="Assignment Name"
android:padding="5dp"
android:textSize="18sp"
android:background="#null" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/assignment_name"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="43dp"
android:orientation="horizontal"
android:layout_below="#id/assignment_name"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout">
<Spinner
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/class_spinner"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar"
android:layout_weight="1"
android:background="#null"/>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#c0c0c0"/>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/due_date_edittext"
android:padding="5dp"
android:focusable="false"
android:hint="Due Date"
android:textSize="16sp"
android:background="#null" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/linearLayout"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/linearLayout"
android:layout_alignParentStart="true"
android:id="#+id/percentCompleteLayout"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Completion"
android:padding="5dp"
android:textColor="#color/black"
android:textSize="15sp"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/percentComplete"
android:layout_marginBottom="1dp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/percentCompleteLayout"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/extra_homework_info"
android:hint="Extra Infomation"
android:textSize="16sp"
android:layout_below="#id/percentCompleteLayout"
android:layout_alignParentStart="true"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#null" />
</RelativeLayout>
spinner_layout.xml*
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:gravity="left"
android:padding="5dip"
android:textColor="#android:color/black"
android:background="#android:color/transparent"
/>
I'm wondering if there is a way to fix this and have the spinner display the default / user choice. If you need any more of the code, all of it can be found in the GitHub. Thanks in advance for all answers!
Solution: Try loading the classes prior to starting the activity, for example in the MainActivity. Then pass the values along through an intent.
Example:
MainActivty.java
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launch Add Homework Activity
Intent intent = new Intent(MainActivity.this, addAssignment.class);
intent.putExtra("classListNames", classListNames);
startActivity(intent);
...
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
classList.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i(TAG, "Class loaded: " + mClass.getClassName());
classList.add(mClass);
classListNames.add(mClass.getClassName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Error: " + databaseError.getMessage());
}
});
addAssignment.java
// Gets class list
Bundle extras = getIntent().getExtras();
classListNames = extras.getStringArrayList("classListNames");
...
mDueClass = (Spinner) findViewById(R.id.class_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classListNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
Cause: After some debugging, I discovered the cause of the problem to be timing differences. The app would request the classes be sent, create the spinner, then load the classes. The difference in timing was milliseconds, but just enough to cause the problem.
i'm making a kind of a form app for my end work for school,
but as you can see in the picture, it ain't going verry well.
I'm trying to save all the date from the textviews into a toast message so i can later on put it into a text file.
But now the Toast file says that all my data is "false"
please help me..
http://prntscr.com/7b4how
package com.jan.energyservice;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Nieuw_huis1 extends ActionBarActivity {
EditText tekst;
String s = "jantest";//AlgemeneGegevens.getFilename();
String uitvoer;
private String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nieuw_huis1);
setupVolgendePagina();
}
private void SlaOp(String String, String String2, String String3, String String4, String String5,
String String6, String String7, String String8, int rdbgrouphuisstatus, String String10,
String String11, String String12, String String13, String String14, String String15,
String String16, String String17, String Titel) {
try{
uitvoer += Titel + "\n";
save(String,String10);
save(String2,String11);
save(String3,String12);
save(String4,String13);
save(String6,String15);
save(String7,String16);
save(String8,String17);
save(rdbgrouphuisstatus);
toonresultaat();
}
catch (Exception e) {
}
}
private void toonresultaat() {
// TODO Auto-generated method stub
Toast.makeText(this, uitvoer,Toast.LENGTH_LONG ).show();
}
private void save(int rdbgrouphuisstatus) {
// TODO Auto-generated method stub
}
private void save(String invoerTekst, String label) {
try {
uitvoer += label + "\n" + invoerTekst;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setupVolgendePagina() {
Button Movebutton = (Button) findViewById(R.id.btnVolgendePagina1);
// 2 click listener to run code
Movebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent =(new Intent(Nieuw_huis1.this,Nieuw_huis2.class));
SlaOp(getText(R.id.txtProjectNaam).toString(),getText(R.id.txtKenmerk).toString(),getText(R.id.txtAdres).toString(),
getText(R.id.txtGemeente).toString(),getText(R.id.txtKlantNaam).toString(),getText(R.id.txtDatumBezoek).toString(),
getText(R.id.txtNaamAdviseur).toString(),getText(R.id.txtHuisnummer).toString(),R.id.rdbgroupHuisStatus,
getText(R.id.tvProjectnaam).toString(),getText(R.id.tvKenmerk).toString(),getText(R.id.tvAdres).toString(),
getText(R.id.tvGemeente).toString(),getText(R.id.tvKlantnaam).toString(),getText(R.id.tvDatumBezoek).toString(),
getText(R.id.tvNaamAdviseur).toString(),getText(R.id.tvHuisnummer).toString(),getText(R.id.tvAdresgegevens).toString());
startActivity(intent);
}
});
}
public void save(View view){
//data = tekst;
try {
FileOutputStream fOut = openFileOutput(s,Context.MODE_PRIVATE);
new PrintStream(fOut).println("Naam van eerste ding");
fOut.write(data.getBytes());
fOut.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nieuw_huis1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is my xml file
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.jan.energyservice.Nieuw_huis1" >
<TextView
android:id="#+id/tvAdresgegevens"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/adresgegevens"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/tvProjectnaam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/projectnaam"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtProjectNaam"
android:layout_width="340dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tvKenmerk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/kenmerk"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtKenmerk"
android:layout_width="365dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text" />
<TextView
android:id="#+id/tvAdres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/adres"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtAdres"
android:layout_width="370dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text|textPersonName" />
<TextView
android:id="#+id/tvGemeente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gemeente"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtGemeente"
android:layout_width="356dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date|text" />
<TextView
android:id="#+id/tvKlantnaam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/klantnaam"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtKlantNaam"
android:layout_width="356dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvDatumBezoek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/datumbezoek"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtDatumBezoek"
android:layout_width="357dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date" />
<TextView
android:id="#+id/tvNaamAdviseur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/naamadviseur"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtNaamAdviseur"
android:layout_width="368dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvHuisnummer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Huisnummer" />
<EditText
android:id="#+id/txtHuisnummer"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<RadioGroup
android:id="#+id/rdbgroupHuisStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rdbVerhuur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/Verhuur" />
<RadioButton
android:id="#+id/rdbVerkoop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/Verkoop" />
<RadioButton
android:id="#+id/rdbImmo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/Immo" />
</RadioGroup>
<Button
android:id="#+id/btnVolgendePagina1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/VolgendePagina" />
</TableLayout>
this is what i edited after your responses.. but still not working
public void onClick(View v) {
Intent intent =(new Intent(Nieuw_huis1.this,Nieuw_huis2.class));
EditText txtProjectnaam = (EditText) findViewById(R.id.txtProjectNaam);
EditText txtKenmerk = (EditText) findViewById(R.id.txtKenmerk);
EditText txtAdres = (EditText) findViewById(R.id.txtAdres);
EditText txtNaamAdviseur = (EditText) findViewById(R.id.txtNaamAdviseur);
EditText txtHuisnummer = (EditText) findViewById(R.id.txtHuisnummer);
EditText txtGemeente = (EditText) findViewById(R.id.txtGemeente);
EditText txtKlantnaam = (EditText) findViewById(R.id.txtKlantNaam);
EditText txtDatumBezoek = (EditText) findViewById(R.id.txtDatumBezoek);
TextView tvProjectnaam = (TextView) findViewById(com.jan.energyservice.R.string.projectnaam);
TextView tvKenmerk = (TextView) findViewById(com.jan.energyservice.R.string.kenmerk);
TextView tvAdres = (TextView) findViewById(com.jan.energyservice.R.string.projectnaam);
TextView tvGemeente = (TextView) findViewById(com.jan.energyservice.R.string.gemeente);
TextView tvKlantnaam = (TextView) findViewById(com.jan.energyservice.R.string.klantnaam);
TextView tvDatumBezoek = (TextView) findViewById(com.jan.energyservice.R.string.datumbezoek);
TextView tvNaamAdviseur = (TextView) findViewById(com.jan.energyservice.R.string.naamadviseur);
TextView tvHuisnummer = (TextView) findViewById(com.jan.energyservice.R.string.Huisnummer);
TextView tvAdresGegevens = (TextView) findViewById(com.jan.energyservice.R.string.adresgegevens);
SlaOp(txtProjectnaam.getText().toString(),txtKenmerk.getText().toString(),txtAdres.getText().toString(),
txtGemeente.getText().toString(),txtKlantnaam.getText().toString(),txtDatumBezoek.getText().toString(),
txtNaamAdviseur.getText().toString(),txtHuisnummer.getText().toString(),R.id.rdbgroupHuisStatus,
tvProjectnaam.getText().toString(),tvKenmerk.getText().toString(),tvAdres.getText().toString(),
tvGemeente.getText().toString(),tvKlantnaam.getText().toString(), tvDatumBezoek.getText().toString(),
tvNaamAdviseur.getText().toString(),tvHuisnummer.getText().toString(),
tvAdresGegevens.getText().toString());
startActivity(intent);
}
});
05-30 19:26:34.383: E/AndroidRuntime(898): FATAL EXCEPTION: main
05-30 19:26:34.383: E/AndroidRuntime(898): java.lang.NullPointerException
05-30 19:26:34.383: E/AndroidRuntime(898): at com.jan.energyservice.Nieuw_huis1$1.onClick(Nieuw_huis1.java:115)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.view.View.performClick(View.java:4204)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.view.View$PerformClick.run(View.java:17355)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.os.Handler.handleCallback(Handler.java:725)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.os.Handler.dispatchMessage(Handler.java:92)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.os.Looper.loop(Looper.java:137)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-30 19:26:34.383: E/AndroidRuntime(898): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 19:26:34.383: E/AndroidRuntime(898): at java.lang.reflect.Method.invoke(Method.java:511)
05-30 19:26:34.383: E/AndroidRuntime(898): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-30 19:26:34.383: E/AndroidRuntime(898): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-30 19:26:34.383: E/AndroidRuntime(898): at dalvik.system.NativeStart.main(Native Method)
05-30 19:26:37.943: E/Trace(3262): error opening trace file: No such file or directory (2)
It says something about line 115 which is in SlaOp from the moment i start with the textviews
Inject your view before you use it.
Do this with all view you wanna to use/modify:
EditText txtKenmerk = (EditText) findViewById(R.id.txtKenmerk)
Then:
txtKenmerk.getText().toString();
I check your latest code and you have a problem with your onClick method starting from your TextView's allocations.
It's an error to cast findViewById(com.jan.energyservice.R.string.projectnaam)
to a TextView since it's not a TextView.
What you should really do is (TextView) findViewById(R.id.projectnaam). that what you configured in your activity xml code. (use R.id for all your objects)
R.string is a special location (string.sml) were you can save all your strings.
The null exception that you got is because you tried to get a view that doesn't exist and therefore you textview was null. afterwards you tried to read from a null function and the exception popped.
Not sure what to think about this problem. This method I created for my tab setup called tabSetUp(), I created a while ago, and call in my onCreate method, and it has worked successfully since then. Now, I suddenly add code in another area of my main activity, and now I am getting an app crash, saying it is caused by my tab setup method. Does not make sense. Am I missing something? The new code I added has no errors, but does have yellow warnings, saying there might be null pointer exceptions (which I don't really understand). Why is my app crashing? Thanks for your help. LogCat is below.
MainSelectorActivity.java
package com.azurespot.disastertimer.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.View;
import android.widget.Button;
import android.widget.TabWidget;
import com.azurespot.disastertimer.app.tabs.GodzillaTab;
import com.azurespot.disastertimer.app.tabs.NuclearTab;
import com.azurespot.disastertimer.app.tabs.TsunamiTab;
import com.azurespot.disastertimer.app.tabs.VolcanoTab;
import com.azurespot.disastertimer.app.tabs.ZombieTab;
import com.azurespot.disastertimer.app.themedactivities.GodzillaThemedActivity;
import com.azurespot.disastertimer.app.themedactivities.NuclearThemedActivity;
import com.azurespot.disastertimer.app.themedactivities.TsunamiThemedActivity;
import com.azurespot.disastertimer.app.themedactivities.VolcanoThemedActivity;
import com.azurespot.disastertimer.app.themedactivities.ZombieThemedActivity;
public class MainSelectorActivity extends FragmentActivity {
Resources resrc;
FragmentTabHost tabHost;
private Button btnStart;
public static final String TABTIMER = "Tab_and_Timer";
private String selectedTab;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_selector);
tabSetUp();
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToThemedActivity();
}
});
tabListener();
changeTabIndicators();
tabAndTimerPersist();
}
public void tabSetUp() {
resrc = getResources();
// TabHost setup & functionality
tabHost = (android.support.v4.app.FragmentTabHost)findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
//------Zombie tab------
//Creates tab and sets zombie icon in tab
tabHost.addTab(tabHost.newTabSpec("zombie").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_zombie_selected)),
ZombieTab.class, null);
//------Nuclear tab------
//Creates tab and sets nuclear icon in tab
tabHost.addTab(tabHost.newTabSpec("nuclear").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_nuclear_selected)),
NuclearTab.class, null);
//------Tsunami tab------
//Creates tab and sets tsunami icon in tab
tabHost.addTab(tabHost.newTabSpec("tsunami").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_tsunami_selected)),
TsunamiTab.class, null);
//------Godzilla tab------
//Creates tab and sets tsunami icon in tab
tabHost.addTab(tabHost.newTabSpec("godzilla").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_godzilla_selected)),
GodzillaTab.class, null);
//------Volcano tab------
//Creates tab and sets volcano icon in tab
tabHost.addTab(tabHost.newTabSpec("volcano").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_volcano_selected)),
VolcanoTab.class, null);
//set Zombie tab as default (zero based)
tabHost.setCurrentTab(0);
}
// Sets up the tabs to return a value, based on which one is currently selected.
// The int values will be used in the Start button's onClick to go to the corresponding activity.
public void tabListener() {
tabHost.setOnTabChangedListener(new FragmentTabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
selectedTab = tabId;
}
});
}
public void changeTabIndicators() {
tabHost = (android.support.v4.app.FragmentTabHost)findViewById(R.id.tabhost);
TabWidget widget = tabHost.getTabWidget();
for(int i = 0; i < widget.getTabCount(); i++) {
View v = widget.getChildTabViewAt(i);
// // Look for the title view to ensure this is an indicator and not a divider.
// TextView tv = (TextView)v.findViewById(android.R.id.title);
// if(tv == null) {
// continue;
// }
v.setBackgroundResource(R.drawable.tab_selector_color);
}
}
public void goToThemedActivity() {
if (selectedTab.equals("zombie")) {
Intent i = new Intent(MainSelectorActivity.this, ZombieThemedActivity.class);
startActivity(i);
} else if (selectedTab.equals("nuclear")) {
Intent j = new Intent(MainSelectorActivity.this, NuclearThemedActivity.class);
startActivity(j);
} else if (selectedTab.equals("tsunami")) {
Intent k = new Intent(MainSelectorActivity.this, TsunamiThemedActivity.class);
startActivity(k);
} else if (selectedTab.equals("godzilla")) {
Intent l = new Intent(MainSelectorActivity.this, GodzillaThemedActivity.class);
startActivity(l);
} else if (selectedTab.equals("volcano")) {
Intent m = new Intent(MainSelectorActivity.this, VolcanoThemedActivity.class);
startActivity(m);
}
}
#Override
protected void onPause() {
super.onPause();
tabAndTimerPersist();
}
private void tabAndTimerPersist() {
SharedPreferences prefs = getSharedPreferences(TABTIMER, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("zombie", 0);
editor.putInt("nuclear", 0);
editor.putInt("tsunami", 0);
editor.putInt("godzilla", 0);
editor.putInt("volcano", 0);
editor.commit();
}
}
LogCat
1054-1054/com.azurespot.disastertimer.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.azurespot.disastertimer.app/com.azurespot.disastertimer.app.MainSelectorActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.azurespot.disastertimer.app.MainSelectorActivity.tabSetUp(MainSelectorActivity.java:60)
at com.azurespot.disastertimer.app.MainSelectorActivity.onCreate(MainSelectorActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
activity_main_selector.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#7d8794"
tools:context="com.azurespot.disastertimer.app.MainSelectorActivity">
<android.support.v4.app.FragmentTabHost
android:id="#+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"
android:measureAllChildren="true"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal"
android:layout_marginTop="180dp"
android:gravity="center_horizontal">
<NumberPicker
android:id="#+id/numberPicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="0dp" />
<NumberPicker
android:id="#+id/numberPicker2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="0dp" />
<NumberPicker
android:id="#+id/numberPicker3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="0dp" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_alignParentBottom="true"
android:gravity="center" >
<Button
android:id="#+id/btnStart"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ed872d"
android:text="#string/btn_start"
android:onClick="saveAndStartTimer"/>
</RelativeLayout>
</RelativeLayout>
Change this from
tabHost = (android.support.v4.app.FragmentTabHost)findViewById(android.R.id.tabhost);
to
tabHost = (FragmentTabHost)findViewById(R.id.tabhost);
I can't understand why I'm getting this error message. My method IS in the activity class and the spelling is correct.
02-09 18:23:57.211: E/AndroidRuntime(19939): FATAL EXCEPTION: main
02-09 18:23:57.211: E/AndroidRuntime(19939): Process: stacy.example.assignment3_stacy_v1, PID: 19939
02-09 18:23:57.211: E/AndroidRuntime(19939): java.lang.IllegalStateException: Could not find a method startRhythmandAnimation(View) in the activity class stacy.example.assignment3_stacy_v1.Assignment3MainActivity for onClick handler on view class android.widget.Button with id 'startbutton'
MainActivity.java
package stacy.example.assignment3_stacy_v1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
public class Assignment3MainActivity extends Activity {
private View mMileTimeGoal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assignment3_main);
mMileTimeGoal = findViewById(R.id.miletimegoal);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.assignment3_main, menu);
return true;
}
public void startRhythmandAnimation () {
String MileTime = mMileTimeGoal.getContext().toString();
String[] time_array = MileTime.split(":");
int hours = Integer.parseInt(time_array[0]);
int minutes = Integer.parseInt(time_array[1]);
int seconds = Integer.parseInt(time_array[2]);
int duration = 3600 * hours + 60 * minutes + seconds;
int steps_per_second = 3;
int running_rate = duration * steps_per_second;
View rightfoot = findViewById(R.id.rightfoot);
View leftfoot = findViewById(R.id.leftfoot);
rightfoot.setVisibility(View.VISIBLE);
Animation anim = AnimationUtils.makeInChildBottomAnimation(this);
rightfoot.startAnimation(anim);
leftfoot.setVisibility(View.VISIBLE);
leftfoot.startAnimation(anim);
}
public void resetTimetoZeroes () {
String MileTime = mMileTimeGoal.getContext().toString();
//Int MileTime = 0;
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Assignment3MainActivity" >
<ImageView
android:id="#+id/leftfoot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/rightfoot"
android:layout_toLeftOf="#+id/rightfoot"
android:src="#drawable/leftfoot" />
<EditText
android:id="#+id/miletimegoal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:ems="10"
android:inputType="time"
android:hint="Mile Time Goal?" />
<ImageView
android:id="#+id/rightfoot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="74dp"
android:layout_marginRight="36dp"
android:src="#drawable/rightfoot" />
<Button
android:id="#+id/startbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/leftfoot"
android:layout_alignRight="#+id/leftfoot"
android:onClick="startRhythmandAnimation"
android:text="#string/start_button" />
<Button
android:id="#+id/resetbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/startbutton"
android:layout_alignBottom="#+id/startbutton"
android:layout_alignLeft="#+id/rightfoot"
android:text="#string/reset_button"
android:onClick="resetTimetoZeroes" />
You need to include a single View parameter for the system to find your method:
public void startRhythmandAnimation (View view)