I have a class extends View and I do my drawings there.I open another activity from menu after I finished my drawing. In second activity, there is editText field for username and there is also a save button. I want to make them saved to my SQLite database, first drawing and then the image related to user. How can I do that ? Now this is my code currently and I'm getting an error.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context com.example.mydrawingapp.View.AppView.getContext()' on a null object reference
at com.example.mydrawingapp.SecondActivity$1.onClick(SecondActivity.java:31)
My Database Helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "drawingApp.db";
public static final String TABLE_NAME="saveUser";
public static final String COL_1 = "ID";
public static final String COL_2="username";
public static final String COL_3="image";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE saveUser (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT,image BLOB)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long addImage(String user, byte[] image){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",user);
contentValues.put("image",image);
long res = database.insert("saveUser",null,contentValues);
database.close();
return res;
}
}
This is the code that I have in my Second Activity class:
public class SecondActivity extends AppCompatActivity {
private EditText textUsername;
private Button buttonRegister;
private String username;
private AppView appView;
private DatabaseHelper dbHelper;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textUsername = (EditText) findViewById(R.id.editText);
username = textUsername.getText().toString();
buttonRegister=(Button) findViewById(R.id.saveButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(appView.getContext(),null );
image = appView.saveImage();
dbHelper.addImage(username,image);
}
});
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
private AppView appView;
private AlertDialog.Builder currentAlertDialog;
private ImageView widthImageView;
private AlertDialog dialogLineWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appView = findViewById(R.id.view);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.clearId:
appView.clear();
break;
case R.id.saveId:
openLoginDialog();
break;
case R.id.lineWidth:
showLineWidthDialog();
break;
}
return super.onOptionsItemSelected(item);
}
private void openLoginDialog() {
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent);
}
void showLineWidthDialog() {
currentAlertDialog = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.width_dialog, null);
final SeekBar widthSeekBar = view.findViewById(R.id.widthSeekBar);
Button setLineWidthButton = view.findViewById(R.id.widthDialogButton);
widthImageView = view.findViewById(R.id.imageViewId);
setLineWidthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView.setLineWidth(widthSeekBar.getProgress());
dialogLineWidth.dismiss();
currentAlertDialog = null;
}
});
widthSeekBar.setOnSeekBarChangeListener(widthSeekBarChange);
currentAlertDialog.setView(view);
dialogLineWidth = currentAlertDialog.create();
dialogLineWidth.setTitle("Set Line Width");
dialogLineWidth.show();
}
SeekBar.OnSeekBarChangeListener widthSeekBarChange = new SeekBar.OnSeekBarChangeListener() {
Bitmap bitmap = Bitmap.createBitmap(400, 100, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Paint p = new Paint();
p.setColor(appView.getDrawingColor());
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeWidth(progress);
bitmap.eraseColor(Color.WHITE);
canvas.drawLine(30, 50, 370, 50, p);
widthImageView.setImageBitmap(bitmap);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
}
your context is null so you need initialize that in this way:
public class SecondActivity extends AppCompatActivity {
private EditText textUsername;
private Button buttonRegister;
private String username;
private AppView appView;
private DatabaseHelper dbHelper;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textUsername = (EditText) findViewById(R.id.editText);
username = textUsername.getText().toString();
buttonRegister=(Button) findViewById(R.id.saveButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(SecondActivity.this ,null ); // change this line
image = appView.saveImage();
dbHelper.addImage(username,image);
}
});
}
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(**appView**.getContext(),null );
image = appView.saveImage();
dbHelper.addImage(username,image);
}
appView<-- this is null at the point of click initialize this first
Related
I am very very tired
I can't change visibility or an object in the fragment from the class controller
exmple addIteamsAutomatic.progressBar.setVisibility(View.GONE); return nullpointer
FragmentAddIteamsAutomatic :
public class FragmentAddIteamsAutomatic extends Fragment {
private EditText ssid, paswd;
public TextView afichage;
public Button parainage;
public Button validation;
public ProgressBar progressBar ;
public LinearLayout linearLayoutParm;
public static String sSSID,pWD;
private ControllerAddIteam controleAdd=null;
public FragmentAddIteamsAutomatic()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.add_iteams_automatic, container, false);
controleAdd.getInstance(getActivity());
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ssid = (EditText) view.findViewById(R.id.ssid);
paswd = (EditText) view.findViewById(R.id.password);
parainage = (Button) view.findViewById(R.id.btnParainage);
validation = (Button) view.findViewById(R.id.btnValid);
afichage = (TextView) view.findViewById(R.id.affichage);
linearLayoutParm = (LinearLayout) view.findViewById(R.id.linearLayParam);
progressBar.setVisibility(View.GONE);
afichage.setVisibility(View.GONE);
validation.setVisibility(View.GONE);
parainage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sSSID = ssid.getText().toString();
pWD = paswd.getText().toString();
if (sSSID.equals(""))
Toast.makeText(getActivity(), "Vous Dever Remplir Tous les champs", Toast.LENGTH_LONG).show();
else
parainer();
}
});
validation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
controleAdd.addSwitchToBase();
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
ControllerAddIteam.accesDistant.send("getIteams", new JSONArray());
// finish();
}
});
return view;
}
private void parainer(){
controleAdd.getInstanceExecuteHandle();
}
}
ControllerAddIteam :
public class ControllerAddIteam {
private static ControllerAddIteam instanceAdd = null;
private static Context context;
private static WifiUtils wifiUtils;
public static String SSID = null;
public static AccesDistant accesDistant;
public static Handler mHandler;
public static final ControllerAddIteam getInstance(Context context) {
if (context != null)
ControllerAddIteam.context = context;
if (ControllerAddIteam.instanceAdd == null) {
ControllerAddIteam.instanceAdd = new ControllerAddIteam();
accesDistant = new AccesDistant();
}
return ControllerAddIteam.instanceAdd;
}
public static void getInstanceExecuteHandle() {
new ParainageHandle().execute();
}
static class ParainageHandle extends AsyncTask<String, String, String> {
FragmentAddIteamsAutomatic addIteamsAutomatic=new FragmentAddIteamsAutomatic();
#Override
protected void onPreExecute() {
super.onPreExecute();
addIteamsAutomatic.progressBar.setVisibility(View.GONE);
addIteamsAutomatic.afichage.setVisibility(View.GONE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
addIteamsAutomatic.progressBar.setVisibility(View.GONE);
if(s.equals("valid"))
{
addIteamsAutomatic.linearLayoutParm.setVisibility(View.GONE);
addIteamsAutomatic.validation.setVisibility(View.VISIBLE);
addIteamsAutomatic.parainage.setVisibility(View.GONE);
}
else if(s.equals("notvalid"))
{
addIteamsAutomatic.parainage.setVisibility(View.VISIBLE);
}
}
#Override
protected void onProgressUpdate(String... values) {
addIteamsAutomatic.afichage.setVisibility(View.VISIBLE);
addIteamsAutomatic.progressBar.setVisibility(View.VISIBLE);
if (values[0].equals("actwifi")) {
if (values[1].equals("true"))
addIteamsAutomatic.afichage.setText("WIFI DEJA ACTIVEE");
else
addIteamsAutomatic.afichage.setText("ACTIVATION WIFI EN COURS...");
} else if (values[0].equals("scan"))
addIteamsAutomatic.afichage.setText("START SCAN FOR Iteams STiTo ... Please Wait");
else if (values[0].equals("find"))
addIteamsAutomatic.afichage.setText("STiTo : "+getTypeFromSsid(SSID)+" DETECTEE : "+SSID);
else if (values[0].equals("connect"))
addIteamsAutomatic.afichage.setText("CONNECTION WITH " + SSID + "En cours ...");
else if (values[0].equals("connectOk"))
addIteamsAutomatic.afichage.setText("CONNECTION WITH " + SSID + "ETABLISHED");
else if (values[0].equals("connectKo"))
addIteamsAutomatic.afichage.setText("PROBLEM OF CONNECTION WITH " + SSID);
else if (values[0].equals("config")) {
addIteamsAutomatic.afichage.setText("SENDING OF CONFIGURATION TO: "+getTypeFromSsid(SSID)+"AND SAVING DATA");
accesDistant.sendConfig(addIteamsAutomatic.sSSID,addIteamsAutomatic.pWD);
....
You declare fragment in AsyncTask and doesn't call replace or add, it mean this fragment never show and it not call onCreateView
FragmentAddIteamsAutomatic addIteamsAutomatic=new FragmentAddIteamsAutomatic();
Maybe you should pass reference addIteamsAutomatic to class ControllerAddIteam. but please make sure it will be call on MainThread, because AsyncTask has method doInBackground in background Thread. best practice is wrap fragment reference by WeakReference
public class AddIteamActivity extends AppCompatActivity {
ViewPager pager;
TabLayout tab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_iteam);
pager = findViewById(R.id.pager);
tab = findViewById(R.id.tab);
AddIteamsAdapter viewPagerAdapter = new AddIteamsAdapter(getSupportFragmentManager());
pager.setAdapter(viewPagerAdapter);
tab.setupWithViewPager(pager);
}
}
I am developing an app quote and I am using a local database to import the quotes.
This is the 4 tables made in sqldatabase.
enter image description here
and in here cobined
Table Database
my table name is "be.db"
i put in the asset folder in android studio
as you can see in the picture the title "Life" has more than 1 quote thats
because in the app when i want to click the item "life" i want it to show me the first quote then i slide to another quote here is front of the app
front page of app
the problem i dont know how to import multiple or 3 tables from sqldatabase i only know how to import one as you can see below this my code in my class "DatabaseHelper" in android studio:
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DBNAME="be.db";
public static final String DBLOCATION=Environment.getDataDirectory()+"/data/com.example.z210.story/databases/";
private Context mcontext;
private SQLiteDatabase mDatabase;
public DataBaseHelper(Context context) {
super(context,DBNAME,null,1);
this.mcontext=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDatabase() {
//l'acces au notre base de donnees
String dbPath=mcontext.getDatabasePath(DBNAME).getPath();
if(mDatabase!=null && mDatabase.isOpen()){
return;
}
mDatabase=SQLiteDatabase.openDatabase(dbPath,null,SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabbase(){
if(mDatabase !=null){
mDatabase.close();
}
}
public ArrayList getAllTitles(){
ArrayList arrayList=new ArrayList();
openDatabase();
Cursor res=mDatabase.rawQuery("select * from title ",null);
res.moveToFirst();
while(!res.isAfterLast()){
arrayList.add(res.getString(res.getColumnIndex("title")));
res.moveToNext();
}
res.close();
closeDatabbase();
return arrayList;
}
public ArrayList getAllQuotes(){
ArrayList arrayList=new ArrayList();
openDatabase();
Cursor res=mDatabase.rawQuery("select * from quote ",null);
res.moveToFirst();
while(!res.isAfterLast()){
arrayList.add(res.getString(res.getColumnIndex("quote")));
res.moveToNext();
}
res.close();
closeDatabbase();
return arrayList;
}
public String get_full_story(String title){
String full_story;
openDatabase();
Cursor res =mDatabase.rawQuery("select * from title where quote like '"+getAllQuotes() +"'",null);
res.moveToFirst();
full_story=res.getString(res.getColumnIndex("quote"));
res.close();
closeDatabbase();
return full_story;
}
}
and here is my code in the main activity
public class MainActivity extends AppCompatActivity {
DataBaseHelper db =new DataBaseHelper (this);
private DrawerLayout mDrawerLayout;
TextView textViewSub,textView3;
Typeface tf1,tf2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView)findViewById(R.id.list);
File database=getApplicationContext().getDatabasePath(db.DBNAME);
if(false==database.exists()) {
db.getDatabaseName();
if (copyDatabase(this)) {
} else {
return;
}
}
ArrayList listTitles=db.getAllTitles();
ArrayList listTitle=db.getAllQuotes();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,R.layout.row_itm,R.id.textView3,listTitles);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String az=String.valueOf(parent.getItemAtPosition(position));
Intent intent=new Intent(MainActivity.this,ShowActivity.class);
intent.putExtra("p",az);
startActivity(intent);
}
});
mDrawerLayout = findViewById(R.id.drawer);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
}
);
textViewSub=(TextView)findViewById(R.id.textViewSub);
textView3=(TextView)findViewById(R.id.textView3);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.para);
final String[] itm=getResources().getStringArray(R.array.index);
(this,R.layout.row_itm,R.id.textView3,itm);
tf1=Typeface.createFromAsset(getAssets(),"orangeblossoms.ttf");
textViewSub.setTypeface(tf1);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream=context.getAssets().open(db.DBNAME);
String outFileName=db.DBLOCATION+db.DBNAME;
OutputStream outputStream=new FileOutputStream(outFileName);
byte[] buff=new byte[1024];
int lenght=0;
while ((lenght=inputStream.read(buff))>0){
outputStream.write(buff,0,lenght);
}
outputStream.flush();
outputStream.close();
return true;
} catch (Exception e) {
return false;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public void error(View view) {
finish();
}
public void favo(View view) {
}
}
Sir,
It should be using array of String or class/object to retrieve the result instead of string only.
Your SQL call return the result set cursor instead of String. Conceptually wrong .
Hey I've just upgraded my app to AppCompat v22.1.0 and got this exception
Caused by: java.lang.IllegalArgumentException: AppCompat does not support the current theme features
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:360)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:246)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)
I found soln. here https://stackoverflow.com/a/29790071/2781359
Still the problem wasn't solved because I was calling the setContentView after super.onCreate, in the ConnectionWifiEditActivity Class.
When I changed this it throws NullPointerException
How Can I Solve this?
Caused by: java.lang.NullPointerException
at Client.Activity.connection.ConnectionEditActivity.onResume(ConnectionEditActivity.java:46)
at Client.Activity.connection.ConnectionWifiEditActivity.onResume(ConnectionWifiEditActivity.java:81)
ConnectionWifiEditActivity
public class ConnectionWifiEditActivity extends ConnectionEditActivity implements OnClickListener
{
private ConnectionWifi connection;
private EditText host;
private EditText port;
Button scan;
ListView lv;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.connectionwifiedit);
lv = (ListView) findViewById(android.R.id.list);
this.connection = (ConnectionWifi) connectionParam;
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.host = (EditText) this.findViewById(R.id.host);
this.port = (EditText) this.findViewById(R.id.port);
SnackbarManager.show(
Snackbar.with(getApplicationContext()) // context
.type(SnackbarType.MULTI_LINE) // Set is as a multi-line snackbar
.text(R.string.tip) // text to be displayed
.duration(Snackbar.SnackbarDuration.LENGTH_INDEFINITE)
, this);
}
public void Save(View v){
this.finish();
}
#Override
public void onClick(View v)
{
}
protected void onResume()
{
super.onResume();
this.host.setText(this.connection.getHost());
this.port.setText(Integer.toString(this.connection.getPort()));
}
protected void onPause()
{
super.onPause();
this.connection.setHost(this.host.getText().toString());
this.connection.setPort(Integer.parseInt(this.port.getText().toString()));
}}
ConnectionEditActivity
public static Connection connectionParam;
private Connection connection;
private EditText name;
private EditText password;
public class ConnectionEditActivity extends AppCompatActivity implements OnClickListener
{
public static Connection connectionParam;
private Connection connection;
private Button save;
private EditText name;
private EditText password;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.connection = connectionParam;
this.name = (EditText) this.findViewById(R.id.name);
this.password = (EditText) this.findViewById(R.id.password);
}
protected void onResume()
{
super.onResume();
this.name.setText(this.connection.getName());
this.password.setText(this.connection.getPassword());
}
protected void onPause()
{
super.onPause();
this.connection.setName(this.name.getText().toString());
this.connection.setPassword(this.password.getText().toString());
}
public void onClick(View v)
{
if (v == this.save)
{
this.finish();
}
}
}
Connection
public abstract class Connection implements Comparable<Connection>, Serializable
{
private static final long serialVersionUID = 1L;
public static final int TYPE_COUNT = 2;
public static final int WIFI = 0;
public static final int BLUETOOTH = 1;
private String name;
private String password;
public Connection()
{
this.name = "";
this.password = RemoteItConnection.DEFAULT_PASSWORD;
}
public static Connection load(SharedPreferences preferences, ConnectionList list, int position)
{
Connection connection = null;
int type = preferences.getInt("connection_" + position + "_type", -1);
switch (type)
{
case WIFI:
connection = ConnectionWifi.load(preferences, position);
break;
case BLUETOOTH:
connection = ConnectionBluetooth.load(preferences, position);
break;
}
connection.name = preferences.getString("connection_" + position + "_name", null);
connection.password = preferences.getString("connection_" + position + "_password", null);
return connection;
}
public void save(Editor editor, int position)
{
editor.putString("connection_" + position + "_name", this.name);
editor.putString("connection_" + position + "_password", this.password);
}
public abstract RemoteItConnection connect(RemoteIt application) throws IOException;
public abstract void edit(Context context);
protected void edit(Context context, Intent intent)
{
ConnectionEditActivity.connectionParam = this;
context.startActivity(intent);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public int compareTo(Connection c)
{
return this.name.compareTo(c.name);
}
}
Since you want to get some ui elements in the super method, you have to find a way to define the layout in the superclass. It is the reason because you are getting an NPE as described in the other answers.
You can use the setContentView() in the superclass, using a method to return the layout to use.
In this way you can override the layout in the sub class, overriding the method.
For example you can use something like setContentView(getLayoutId()):
public class ConnectionEditActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(getLayoutId()); //pay attention here...
this.connection = connectionParam;
this.name = (EditText) this.findViewById(R.id.name);
this.password = (EditText) this.findViewById(R.id.password);
}
protected int getLayoutId(){
//....
}
}
And you can override it in other activity, where you can avoid the setContentView method.
public class ConnectionWifiEditActivity extends ConnectionEditActivity{
#Override
protected int getLayoutId(){
return R.layout.connectionwifiedit;
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(); //comment this line
//..
}
}
Just add this to your style (both are needed)
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
and in ConnectionEditActivity you call findViewById BEFORE calling setContentView it will always return null. So your view will be always null.
this.connection = connectionParam;
this.name = (EditText) this.findViewById(R.id.name);
this.password = (EditText) this.findViewById(R.id.password);
Little trick is to use override fun onPostCreate(savedInstanceState: Bundle?) method in you parent to find views
I'm trying to configure the button1 to change activity, but although I do not detect errors with eclipse, the button does not work, someone can tell me what is wrong thanks.
After the lprimo button there is' another button for data backup, I would not think the problem is caused by the presence of another button.
public class Aggiungi extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_turno,edit_ore;
private TextView edit_mese,edit_anno;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String idturno,anno,mese,turno,ore;
private boolean isUpdate;
Spinner selectedMesi,selectedGiorni;
private final static String MY_PREFERENCES = "MyPref";
private final static String ANNO = "anno";
public void cambia (View view){
final Intent cambioTermini;
cambioTermini = new Intent (this, Cambio.class);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(cambioTermini);
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
Intent intent=getIntent();
String anno = prefs.getString(ANNO, "2014");
btn_save=(Button)findViewById(R.id.save_btn);
edit_mese=(TextView)findViewById(R.id.txtmese);
edit_anno=(TextView)findViewById(R.id.txtanno);
edit_turno=(EditText)findViewById(R.id.turno_editTxt);
edit_ore=(EditText)findViewById(R.id.ore_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
idturno=getIntent().getExtras().getString("ID");
mese=getIntent().getExtras().getString("Mese");
anno=getIntent().getExtras().getString("Anno");
turno=getIntent().getExtras().getString("Turno");
ore=getIntent().getExtras().getString("Ore");
edit_mese.setText(mese);
edit_anno.setText(anno);
edit_turno.setText(turno);
edit_ore.setText(ore);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
mese=edit_mese.getText().toString().trim();
anno=edit_anno.getText().toString().trim();
turno=edit_turno.getText().toString().trim();
ore=edit_ore.getText().toString().trim();
if(anno.length()>0&& mese.length()>0 && turno.length()>0 &&ore.length()>0)
{
saveData();
}
else
As per my understanding, you want to launch 'Cambio' activity on button1 click. Try this.
public class Aggiungi extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_turno,edit_ore;
private TextView edit_mese,edit_anno;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String idturno,anno,mese,turno,ore;
private boolean isUpdate;
Spinner selectedMesi,selectedGiorni;
private final static String MY_PREFERENCES = "MyPref";
private final static String ANNO = "anno";
public void cambia(){
final Intent cambioTermini;
cambioTermini = new Intent (this, Cambio.class);
// Start cambioTermini activity
startActivity(cambioTermini);
// close this activity
finish();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
Intent intent=getIntent();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
cambia();
break;
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class Contact extends Activity
{
public ImageView btnlog1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlog1=(ImageView)findViewById(R.id.imageView2);
btnlog1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent l = new Intent(Contact.this,
AndroidDashboardDesignActivity.class);
startActivity(l);
Contact.this.finish();
}
});
}
}
Use this code and try like this.. This is simple code for intent changing for one activity to another.. let me know your ans..
I was expecting something like:
public void cambia (View view){
final Intent cambioTermini;
cambioTermini = new Intent (this, Cambio.class);
startActivity(cambioTermini);
}
since you have
<Button
android:id="#+id/button1"
//.. other paramters
android:onClick="cambia"
android:text="cambia" />
I'm writing a tip app where the user selects a check, and then on the second activity the subtotal is displayed. However, I'm completely lost on how I display my subtotal. I have a getSubtotal() method but I don't know how to call it.
First Activity
public class TableListActivity extends Activity {
private ListView mListView;
private TableListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_list);
// Find the ListView, create an adapter that reads our list of checks,
// and connect the two
mListView = (ListView)findViewById(R.id.listView);
mAdapter = new TableListAdapter(this, DataStore.CHECKS);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent (TableListActivity.this, PayCheckActivity.class);
intent.putExtra(PayCheckActivity.Extra_check, arg2);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.table_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
// TODO do stuff here
Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}}
Second Activity
public class PayCheckActivity extends Activity{
String Thank;
Button Sign;
Button fifteen;
Button eighteen;
Button twenty;
String sample;
public static final String Extra_check= "abc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paycheck);
Sign = (Button)findViewById(R.id.Sign);
fifteen= (Button)findViewById(R.id.fifteen);
eighteen= (Button)findViewById(R.id.eighteen);
twenty= (Button)findViewById(R.id.twenty);
Sign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank You", Toast.LENGTH_LONG);
msg.show();
}});
fifteen.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank Yolllllu", Toast.LENGTH_LONG);
msg.show();
}});}}
Check.java
public class Check {
private long id;
private String tableName;
private ArrayList<MenuItem> mItems = new ArrayList<MenuItem>();
private boolean hasBeenSigned = false;
public static class MenuItem {
public String name;
public Amount cost;
public MenuItem(String itemDescription, double cost) {
this.name = itemDescription;
this.cost = new Amount(cost);
}
}
public Check(long id, String tableName) {
this.id = id;
this.tableName = tableName;
}
public long getId() {
return id;
}
#Override
public String toString() {
// The ArrayAdapter uses toString to get the text to display in the list item
// We override toString here to display the table name
return tableName;
}
public void addItem(String itemDescription, double cost) {
mItems.add(new MenuItem(itemDescription, cost));
}
public String getTableName() {
return tableName;
}
public Amount getSubtotal() {
double total = 0;
for (MenuItem item : mItems) {
total += item.cost.getRawValue();
}
return new Amount(total);
}
public void markAsSigned() {
hasBeenSigned = true;
}
public int getItemCount() {
return mItems.size();
}
public MenuItem getMenuItemAt(int index) {
return mItems.get(index);
}}
Just a quick hint: You are sending some data to the second activity via Intent (onItemClick). In the second activity in onCreate, you can pick this data and call your getSubtotal method. Since it's not quite clear, what "Check" does, it's up to you how to instantiate it:
public class PayCheckActivity extends Activity{
// ...
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if(intent != null) {
String value = intent.getStringExtra(PayCheckActivity.Extra_check);
Check check = .....
check.getSubtotal()
}
}
// ...
}