how to pass data from notification to activity in android - android-notifications

i need to create two statusbar Notifications.when i click first notification icon., i've to disaply some data(ex.activity1).,if i click second notification icon.,i've to display another data(Ex.activity2).i've created well.But i couldnt able to display data.
My code:
package com.collabera.labs.sai;
import java.util.ArrayList;
import android.R.string;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SimpleNotification extends Activity {
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID_A = 0;
private int SIMPLE_NOTFICATION_ID_B = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Button start = (Button) findViewById(R.id.notifyButton);
//Button cancel = (Button)findViewById(R.id.cancelButton);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// display A
displayNotification("Extra for A", "This is A", "Some text for activity A", MyActivityA.class, SIMPLE_NOTFICATION_ID_A);
// display B
displayNotification("Extra for B", "This is B", "Some text for activity B", MyActivityB.class, SIMPLE_NOTFICATION_ID_B);
}
});
}
private void displayNotification(String extra, String contentTitle, String contentText, Class<?> cls, int id) {
Notification notifyDetails = new Notification(R.drawable.icon, "New Alert!", System.currentTimeMillis());
Intent intent = new Intent(this, cls);
Bundle b=new Bundle();
b.putString("extra", extra);
intent.putExtras(b);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), id, intent, PendingIntent.FLAG_ONE_SHOT);
notifyDetails.setLatestEventInfo(getApplicationContext(), contentTitle, contentText, contentIntent);
mNotificationManager.notify(id, notifyDetails);
}
}
On MyActivityA:
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub);
tv=(TextView)findViewById(R.id.tv);
Bundle b = getIntent().getExtras();
String value = b.getString("extra");
tv.setText(value);
Whats error on this..It didnt displayed the text..

Try this:
First activity:
int requestID = (int) System.currentTimeMillis(); Intent intent = new Intent(this, NotificationReceiverActivity.class); intent.putExtra("data1", "My Data 1"); intent.putExtra("data2", "My Data 2"); PendingIntent pIntent = PendingIntent.getActivity(this, requestID, intent, 0);
Second activity that called from First activity
PUT this in oncreated method
Bundle extras = getIntent().getExtras();
if(extras != null){
String data1 = extras.getString("data1");
String data2 = extras.getString("data2");
Log.e("Ddata1" + data1, data2);
}

Related

how to authenticate and save data in firebase at same time using android studio

i have wrriten a code and getting error in
06-30 23:55:00.702 2499-2499/com.example.parthtiwari.trace E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.parthtiwari.trace, PID: 2499
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null
my code is
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.AuthResult;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private FirebaseAuth fb;
private DatabaseReference databaseReference;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextName, mobile_number,vehicle_number,editTextAddress;
private Button buttonSignup;
private TextView textViewSignin;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fb = FirebaseAuth.getInstance();
if(fb.getCurrentUser() != null){
finish();
startActivity(new Intent(getApplicationContext(),welcome.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
editTextAddress = (EditText) findViewById(R.id.Address);
editTextName = (EditText) findViewById(R.id.name);
mobile_number = (EditText) findViewById(R.id.mobile);
vehicle_number = (EditText) findViewById(R.id.vehicle);
editTextEmail = (EditText) findViewById(R.id.Email);
editTextPassword = (EditText) findViewById(R.id.Password);
buttonSignup = (Button) findViewById(R.id.Signup);
textViewSignin = (TextView) findViewById(R.id.Signin);
progressDialog = new ProgressDialog(this);
FirebaseUser user = fb.getCurrentUser();
buttonSignup.setOnClickListener(this);
textViewSignin.setOnClickListener(this);
}
private void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email",
Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password",
Toast.LENGTH_LONG).show();
return;
}
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
fb.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Successfully registered", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Registration Error", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
saveUserInformation();
}
private void saveUserInformation() {
String name = editTextName.getText().toString().trim();
String mob = mobile_number.getText().toString().trim();
String vehicle = vehicle_number.getText().toString().trim();
String add = editTextAddress.getText().toString().trim();
//creating a userinformation object
userinfo userInformation = new userinfo(name, mob, vehicle, add);
//getting the current logged in user
FirebaseUser user = fb.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
//displaying a success toast
Toast.makeText(this, "Information Saved...", Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View view) {
if(view == buttonSignup){
registerUser();
}
if(view == textViewSignin){
startActivity(new Intent(this, login.class));
}
}
}
Try moving saveUserInformation() into your onCompletionListener.
Looks like saveUserInformation() is called before registration is completed.
fb.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
saveUserInformation(authResult);
Toast.makeText(MainActivity.this, "Successfully
registered",Toast.LENGTH_LONG).show();
progressDialog.dismiss(); }).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Registration Error",
Toast.LENGTH_LONG).show();
progressDialog.dismiss();
});
and change
saveUserInformation(AuthResult authResult)
authResult.getUid();

SharedPreferences within a fragment

Once the user selects an item from a list in another fragment it brings you to this fragment. And I'm having issues trying to save the users rating that was selected. when the user goes back it should be the same rating that was previously selected.
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.Arrays;
public class infoFragment extends Fragment {
TextView degrees;
ImageView image;
String stringtext;
String [] hold;
private RatingBar rating;
SharedPreferences wmbPreference1;
SharedPreferences.Editor editor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.info_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
image = (ImageView) view.findViewById(R.id.imageView);
why can i not use "this"
rating =((RatingBar) view.findViewById(R.id.ratingBar)).setOnRatingBarChangeListener(this);
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
degrees =(TextView)view.findViewById(R.id.textView);
}
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
final int numStars = ratingBar.getNumStars();
editor = wmbPreference1.edit();
editor.putInt("numStars", numStars);
editor.commit();
int ratings = wmbPreference1.getInt("numStars", 0);
}
public void setText(final String string) {
Character[] hold;
if(string == "apple"){
String[] word = { " A \n", "B\n" };
degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
image.setImageResource(R.drawable.APPLE);
}
Should I call onRatingChanged within the conditional statement for it to save?
if(string == "orange"){
String[] word = { " AA\n", "AB\n" };
degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
image.setImageResource(R.drawable.bruce);
}
}
public void sentText(){
new MyTask().execute();
}
private class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
Bundle b = getArguments();
stringtext = b.getString("text");
return null;
}
protected void onPostExecute(String result){setText(stringtext);
}
}
}
Your Fragment should implement OnRatingBarChangeListener:
public class infoFragment extends Fragment implements OnRatingBarChangeListener
The other thing is that setOnRatingChangeListener does not return a value, so you can't assign the return value to rating as you did.
You should do:
rating = (RatingBar) view.findViewById(R.id.ratingBar);
rating.setOnRatingBarChangeListener(this);

How to pass bundle to the fragments in android

I am developing application consists of navigation drawer with swipe tabs
Here i need to pass the bundle to the navigation drawer from my home activity at the time of receiving bundle i am getting nullpointerexception can any one help me
This is my Home activity:
package android.lotus.com.androidmis;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.lotus.mis.modle.MyAppApplication;
import com.lotus.mis.modle.UserDetails;
public class Home extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
Toolbar toolbar;
public static String UserName, userID, FlagList, User_code, Mail_id,
user_reporting_level;
UserDetails ObjUserDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
/**Getting bundle from the LotusLogin screen**/
Bundle bundle = getIntent().getExtras();
UserName = bundle.getString("key_username");
ObjUserDetails = (UserDetails) getIntent().getSerializableExtra("UserDetails");
/**getting user details from the UserDetails modle**/
userID = ObjUserDetails.getUserID();
User_code = ObjUserDetails.getEmpCode();
Mail_id = ObjUserDetails.getEmail();
user_reporting_level = ObjUserDetails.getPOSITION();
/**Setting user details as global user details*/
MyAppApplication mApp = new MyAppApplication();
mApp.setmGlobal_UserID(userID);
mApp.setMGlobal_EmpID(User_code);
mApp.setMGlobal_mailID(Mail_id);
//setting bundle to travels fragment
Bundle travels_bundle = new Bundle();
travels_bundle.putString("key_username", UserName);
travels_bundle.putString("key_userid", userID);
Travels travels_fragment = new Travels();
travels_fragment.setArguments(travels_bundle);
if (user_reporting_level.equalsIgnoreCase("-")) {
mApp.setmGlobal_reporting_level("");
} else {
mApp.setmGlobal_reporting_level(user_reporting_level);
}
FlagList = "3";
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Travels()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
/* if (menuItem.getItemId() == R.id.nav_item_sent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new SentFragment()).commit();
}
*/
if (menuItem.getItemId() == R.id.nav_item_travels) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Travels()).commit();
/** Passing bundle to the travels fragment*/
Bundle travels_bundle = new Bundle();
travels_bundle.putString("key_username", UserName);
travels_bundle.putString("key_userid", userID);
Travels travels_fragment = new Travels();
travels_fragment.setArguments(travels_bundle);
} else if (menuItem.getItemId() == R.id.nav_item_sales) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Sales()).commit();
} else if (menuItem.getItemId() == R.id.nav_item_sales_reports) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new SalesReports()).commit();
} else if (menuItem.getItemId() == R.id.nav_item_voucher) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Voucher()).commit();
} else if (menuItem.getItemId() == R.id.nav_item_daylog) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Daylog()).commit();
} else if (menuItem.getItemId() == R.id.nav_item_leaves) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Leaves()).commit();
} else if (menuItem.getItemId() == R.id.nav_item_complaints) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Complaints()).commit();
}
return false;
}
});
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my home activity bundle i am passing
Bundle travels_bundle = new Bundle();
travels_bundle.putString("key_username", UserName);
travels_bundle.putString("key_userid", userID);
Travels travels_fragment = new Travels();
travels_fragment.setArguments(travels_bundle);
This is my navigation drawer fragment:
package android.lotus.com.androidmis;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.subtabs.travels.Cancelled;
import com.subtabs.travels.Today;
import com.subtabs.travels.Upcoming;
import com.subtabs.travels.History;
public class Travels extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 4 ;
public String UserName,UserID;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,container,false);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**Getting bundle from Home screen of Travels module*/
Bundle travels_bundle = this.getArguments(); //Error occuring place
UserName = travels_bundle.getString("key_username");
UserID = travels_bundle.getString("key_userid");
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 :
/**Sending bundle to the upcoming fragment of Travels module*/
Bundle upcoming_bundle = new Bundle();
upcoming_bundle.putString("key_username",UserName);
upcoming_bundle.putString("key_userid", UserID);
upcoming_bundle.putString("key_TravelFlag","1");
Upcoming upcoming_fragment = new Upcoming();
upcoming_fragment.setArguments(upcoming_bundle);
return new Upcoming();
case 1 : return new History();
case 2 : return new Today();
case 3 : return new Cancelled();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Upcoming";
case 1:
return "History";
case 2:
return "Today";
case 3:
return "Cancelled";
}
return null;
}
}
}
From this navigation drawer fragment i am having the 4 swipe tabs and pass the which was received in above bundle.
Please return the Fragment object.
/**Sending bundle to the upcoming fragment of Travels module*/
Bundle upcoming_bundle = new Bundle();
upcoming_bundle.putString("key_username",UserName);
upcoming_bundle.putString("key_userid", UserID);
upcoming_bundle.putString("key_TravelFlag","1");
Upcoming upcoming_fragment = new Upcoming();
upcoming_fragment.setArguments(upcoming_bundle);
return upcoming_fragment; ////// Changed Here
And also add this code -
/**Getting bundle from Home screen of Travels module*/
Bundle travels_bundle = this.getArguments(); //Error occuring place
UserName = travels_bundle.getString("key_username");
UserID = travels_bundle.getString("key_userid");
After setting the adapter.
EDIT
if (menuItem.getItemId() == R.id.nav_item_travels) {
/** Passing bundle to the travels fragment*/
Bundle travels_bundle = new Bundle();
travels_bundle.putString("key_username", UserName);
travels_bundle.putString("key_userid", userID);
Travels travels_fragment = new Travels();
travels_fragment.setArguments(travels_bundle);
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, travels_fragment).commit();
}

JavaFX obtaining data from table

I have trouble obtaining data from table.
Get items doesn't work, and I'm stuck because there is lack of documentation. I get that Person is table model, but how can I use getFirstName from that maybe that is an answer. I have get but can not use that. Or should I stick to Swing for time being?
Here is a code:
package imenik;
import java.awt.Panel;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* #author Anak1n
*/
public class Imenik extends Application {
Label ime, prezime, brojTelefona, email, mobilni;
TextField imeTxt;
TextField prezimeTxt;
TextField brojTelTxt;
TextField mobilniTxt;
TextField emailTxt;
GridPane panelImenik;
Panel tabela;
Button potvrdi, otkazi, sacuvaj, otvori;
FileChooser fc = new FileChooser();
VBox vbox;
private final TableView<Person> table = new TableView<>();
#Override
public void start(final Stage primaryStage) {
ime = new Label("Ime: ");
prezime = new Label("Prezime: ");
brojTelefona = new Label("Fixni: ");
email = new Label("e-mail: ");
imeTxt = new TextField();
prezimeTxt = new TextField();
brojTelTxt = new TextField();
emailTxt = new TextField();
mobilni = new Label("Mobilni");
mobilniTxt = new TextField();
TableColumn imeT = new TableColumn("Ime");
imeT.setCellValueFactory(
new PropertyValueFactory<Person, String>("firstName")
);
imeT.prefWidthProperty().bind(table.widthProperty().divide(4));
TableColumn prezimeT = new TableColumn("Prezime");
prezimeT.setCellValueFactory(
new PropertyValueFactory<Person, String>("lastName")
);
prezimeT.prefWidthProperty().bind(table.widthProperty().divide(4));
TableColumn brojTelefonaFix = new TableColumn("Fixni");
brojTelefonaFix.setCellValueFactory(
new PropertyValueFactory<Person, String>("fixni")
);
brojTelefonaFix.prefWidthProperty().bind(table.widthProperty().divide(4));
TableColumn brojTelefonaMob = new TableColumn("Mobilni");
brojTelefonaMob.setCellValueFactory(
new PropertyValueFactory<Person, String>("mobilni")
);
brojTelefonaMob.prefWidthProperty().bind(table.widthProperty().divide(4));
TableColumn brTel = new TableColumn("Broj telefona");
brTel.getColumns().addAll(brojTelefonaFix, brojTelefonaMob);
brTel.prefWidthProperty().bind(table.widthProperty().divide(4));
TableColumn emailT = new TableColumn("E-mail");
emailT.setCellValueFactory(
new PropertyValueFactory<Person, String>("email")
);
emailT.prefWidthProperty().bind(table.widthProperty().divide(4));
sacuvaj = new Button("Sacuvaj");
sacuvaj.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.csv");
fc.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fc.showSaveDialog(primaryStage);
if (file != null) {
SaveFile(table.getItems().toString(), file);
}
}
});
otvori = new Button("Otvori");
vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
tabela = new Panel();
panelImenik = new GridPane();
panelImenik.setAlignment(Pos.TOP_CENTER);
panelImenik.setHgap(10);
panelImenik.setVgap(10);
panelImenik.setPadding(new Insets(25, 25, 25, 25));
potvrdi = new Button("Potvrdi");
potvrdi.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
// ObservableList<Person> data = table.getItems();
table.getItems().add(new Person(
imeTxt.getText(),
prezimeTxt.getText(),
emailTxt.getText(),
brojTelTxt.getText(),
mobilniTxt.getText()
));
prezimeTxt.setText("");
imeTxt.setText("");
brojTelTxt.setText("");
emailTxt.setText("");
mobilniTxt.setText("");
}
});
table.getColumns().addAll(imeT, prezimeT, brTel, emailT);
otkazi = new Button("Ponisti");
otkazi.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
prezimeTxt.setText("");
imeTxt.setText("");
brojTelTxt.setText("");
emailTxt.setText("");
mobilniTxt.setText("");
System.out.print(table.getColumns().get(0));
}
});
vbox.getChildren().addAll(table, panelImenik);
dodaj();
Scene scene = new Scene(vbox, 411, 600);
//table.setItems(data);
primaryStage.setTitle("Imenik");
scene.getStylesheets().add(Imenik.class.getResource("pozadina.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
private void dodaj() {
panelImenik.add(ime, 0, 0);
panelImenik.add(imeTxt, 1, 0);
panelImenik.add(prezime, 0, 1);
panelImenik.add(prezimeTxt, 1, 1);
panelImenik.add(brojTelefona, 0, 2);
panelImenik.add(brojTelTxt, 1, 2);
panelImenik.add(mobilni, 0, 3);
panelImenik.add(mobilniTxt, 1, 3);
panelImenik.add(email, 0, 4);
panelImenik.add(emailTxt, 1, 4);
panelImenik.add(potvrdi, 1, 5);
panelImenik.add(otkazi, 0, 5);
panelImenik.add(sacuvaj, 2, 5);
panelImenik.add(otvori, 3, 5);
}
private void dodajUTabelu() {
}
public class Person {
private final SimpleStringProperty ime;
private final SimpleStringProperty prezime;
private final SimpleStringProperty email;
private final SimpleStringProperty fixni;
private final SimpleStringProperty mobilni;
private Person(String ime, String prezime, String email, String fixni, String mobilni) {
this.ime = new SimpleStringProperty(ime);
this.prezime = new SimpleStringProperty(prezime);
this.email = new SimpleStringProperty(email);
this.fixni = new SimpleStringProperty(fixni);
this.mobilni = new SimpleStringProperty(mobilni);
}
public String getFirstName() {
return ime.get();
}
public void setFirstName(String fName) {
ime.set(fName);
}
public String getLastName() {
return prezime.get();
}
public void setLastName(String fName) {
prezime.set(fName);
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
public String getFixni() {
return fixni.get();
}
public void setFixni(String fName) {
fixni.set(fName);
}
public String getMobilni() {
return mobilni.get();
}
public void setMobilni(String fName) {
mobilni.set(fName);
}
}
private void SaveFile(String content, File file) {
try {
FileWriter fileWriter = null;
fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
System.out.print("Nije moguce");
}
}
}
You get items from the table by row, in this case that would be a person object. Then you use the get methods of the Person class to access fields. I'm guessing you want to use them in SaveFile(String, File) You should change it to something like saveFile(ObservableList<Person> persons, File file). Then you write the file something like
for (Person p : persons){
fileWriter.write(p.getFirstName()+","+
p.getLastName()/*etc..*/+"\n");
}
I did something like this. Got a hint on oracle forum :)
for (Person person : table.getItems()) {
String firstName = person.getFirstName();
String lastName = person.getLastName();
String email = person.getEmail();
String broj = person.getFixni();
String mob = person.getMobilni();
When i have them i will save them easily :)

Where I can find example of SQLite database file or dump of it? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I really need a sqlite database file for studies.
I'm creating an application in C# and I need a database with many tables, field, views, indexes, constraints and so on. And I don't want to create it myself using sqlite command line tool.
So I suppose may be someone can say where I can find such file, may be different applications or examples, or even can send me their own database file. I will appreciate any help.
There is a nice sample database called Chinook. It's trying to be the modern example to replace NorthWind. They have versions for different database servers including SQLite.
Homepage, DB diagram, etc.. http://chinookdatabase.codeplex.com/
Github (seems more updated than CodePlex) https://github.com/lerocha/chinook-database
Latest SQLite download to date of post: https://chinookdatabase.codeplex.com/releases/view/55681#fileDownload6
Download SQLite Sample Database to get the Chinook database file directly http://www.sqlitetutorial.net/sqlite-sample-database/
More SQLite related projects and samples on CodePlex http://www.codeplex.com/site/search?query=sqlite&ac=8
Also, check this sample in the SQLite .NET client forums (attached to first post)
Getting the Microsoft EFQuerySamples project to work with SQLite
Maybe a GUI tool to create database stuff will make starting easier, check this one, free for personal use
http://www.sqliteexpert.com/
Personally, I create SQLite databases for testing NHibernate mappings. Usually I create my classes and mappings then use the mappings to generate schema to a new SQLite file (or in memory database, more often) and use that. Most NHibernate introduction articles do that as well.
SQLite is whidely used by many applications so I am pretty sure very lot examples can be found on your computer. For example, on my Win10 PC if I search in "c:\Users\Konstantin" (my profile) for files with:
file name mask: *.sqlite;*.db
text inside: SQLite format 3
I am currently getting 785 results. Most of them, which have that text in the beginning - it is 99% SQLite database files. Particularly I see that it is used by skype, viber, dropbox, office and firefox.
I used sqlightCrud operation
First creat database class.
package com.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
public class DataBaseSampleActivity {
/** for database */
static final String DataBaseName = "EmployeDB";
/** for employee table */
static final String EmployeTable = "Employees";
static final String ColEmpID = "EmpId";
static final String ColEmpName = "EmpName";
static final String ColEmpAge = "EmpAge";
static final String ColDept = "Dept";
/** for department table */
static final String DeptTable = "Department";
static final String ColDeptID = "DeptId";
static final String ColDeptName = "DeptName";
public static final int DATABASE_VERSION = 2;
//private static final String KEY_ROWID = "_id";
private static final String EMPLOYEE_TABLE_CREATE ="Create table " + EmployeTable +
//"(_id INTEGER UNIQUE," + [old code]
"("+ColEmpID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
ColEmpName + " VARCHAR(15) ," +
ColEmpAge + " INT(15) ," +
ColDept + " VARCHAR(15)) ";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DataBaseSampleActivity(Context ctx){
Log.i("test****", "**test***");
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context){
super(context, DataBaseName , null, DATABASE_VERSION);
Log.i("context","context");
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(EMPLOYEE_TABLE_CREATE);
Log.i("************", "table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("tag", "Upgrading database from version " + oldVersion + " to "+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + EmployeTable);
onCreate(db);
}
};
public DataBaseSampleActivity open() throws SQLException{
db = DBHelper.getWritableDatabase();
Log.i("open", "message");
return this;
}
public void close(){
DBHelper.close();
}
//public long insert(Integer empid, String empname, Integer empage, String empdept) {
public long insert(String empname, Integer empage, String empdept) {
Log.i("**** suruchitest **** ","*** test ***");
ContentValues initialValues = new ContentValues();
//initialValues.put(ColEmpID, empid);
initialValues.put(ColEmpName, empname);
initialValues.put(ColEmpAge, empage);
initialValues.put(ColDept, empdept);
return db.insert(EmployeTable, null, initialValues);
}
public Cursor getEmpValues(){
Cursor mCursor = db.query(EmployeTable, null, null, null, null, null, null);
return mCursor;
}
public boolean deleteEmpList(long rowId){
Toast.makeText(context, "deleted", 2000).show();
return db.delete(EmployeTable, ColEmpID +" = " + rowId, null) > 0;
}
public boolean updateEmplist(String empname, Integer empage, String empdept, Integer rowid){
ContentValues initialValues = new ContentValues();
Log.i("##### "+rowid,""+empname+" "+empage+" "+empdept);
//initialValues.put(ColEmpID, rowid);
initialValues.put(ColEmpName,empname);
initialValues.put(ColEmpAge,empage);
initialValues.put(ColDept,empdept);
try{
int b = db.update(EmployeTable, initialValues, ColEmpID+ " = " + rowid, null);
Log.i("update", "up "+rowid+" ddd "+b);
return true;
}catch (Exception e){
Log.d("asdfasdfsadfasdf", "_--___--__--_=-_");
return false;
}
}
}
2. create Main Activity
package com.db;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button buttonsubmit;
EditText empid,empname,empage,empdept;
String emp_name, emp_dept;
//Integer emp_id,emp_age;
Integer emp_age;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonsubmit = (Button) findViewById(R.id.btnSubmit);
buttonsubmit.setOnClickListener(this);
// empid =(EditText) findViewById(R.id.empid);
empname =(EditText) findViewById(R.id.empname);
empage =(EditText) findViewById(R.id.empage);
empdept =(EditText) findViewById(R.id.empdpt);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBaseSampleActivity dbObj = new DataBaseSampleActivity(getApplicationContext());
// String Emp_ids = empid.getText().toString();
// emp_id = Integer.parseInt(Emp_ids);
//emp_id = empid.getText().toString();
String Emp_ages = empage.getText().toString();
emp_age = Integer.parseInt(Emp_ages);
//emp_age = empage.getText().toString();
emp_name = empname.getText().toString();
emp_dept = empdept.getText().toString();
try {
Log.i("try", "message");
dbObj.open();
//long temp = dbObj.insert(emp_id, emp_name, emp_age, emp_dept);
long temp = dbObj.insert(emp_name, emp_age, emp_dept);
//Toast.makeText(getApplicationContext(), "temp"+temp, 3000).show();
dbObj.close();
Intent intent = new Intent(this,ShowListView.class);
startActivity(intent);
} catch (Exception e) {
// TODO: handle exception
Log.i("catch", "message");
}
}
}
2. Create listclass to show tha data
package com.db;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ShowListView extends Activity {
ArrayList<String> arrname = new ArrayList<String>();
ArrayList<String> arrage = new ArrayList<String>();
ArrayList<String> arrdept = new ArrayList<String>();
ArrayList<Integer> arrRowId = new ArrayList<Integer>();
ArrayList<Integer> arrDelId = new ArrayList<Integer>();
Array[] arr;
Button deleteBtn;
Button btnadd;
int index = 0;
public int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emplist);
//Toast.makeText(getApplicationContext(), "LIST VIEW", 5000).show();
ToGetCursorValues();
}
public void ToGetCursorValues(){
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
try {
Cursor cur = db.getEmpValues();
cur.moveToFirst();
arrRowId.clear();
arrname.clear();
arrage.clear();
arrdept.clear();
while (!cur.isAfterLast()) {
arrRowId.add(cur.getInt(cur.getColumnIndex(db.ColEmpID)));
arrname.add(cur.getString(cur.getColumnIndex(db.ColEmpName)));
arrage.add(cur.getString(cur.getColumnIndex(db.ColEmpAge)));
arrdept.add(cur.getString(cur.getColumnIndex(db.ColDept)));
cur.moveToNext();
}
//Log.i("#####","col "+arrlist.size());
//Toast.makeText(getApplicationContext(), "* "+arrname.size()+","+arrage.size()+","+arrdept.size(), 5000).show();
//Toast.makeText(getApplicationContext(), "***** "+arrRowId.get(0), 2000).show();
} catch (Exception e) {
// TODO: handle exception
}
ListView lst = (ListView) findViewById(R.id.mylist);
lst.setAdapter(new ListAdapter(getApplicationContext()));
db.close();
}
public class ListAdapter extends BaseAdapter implements OnCheckedChangeListener,OnClickListener{
private LayoutInflater inflater = null;
public ListAdapter(Context c){
Log.i("Context","Context");
inflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//return 0;
return arrname.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder{
TextView empnameview;
TextView empageview;
TextView empdeptview;
CheckBox empchkbox;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i("*view","view*");
ViewHolder vh;
//ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
Log.i("*null1*","*null1*");
vh = new ViewHolder();
convertView = inflater.inflate(R.layout.customlist, null);
Log.i("*null2*","*null2*");
pos = position;
vh.empnameview = (TextView) convertView.findViewById(R.id.ename);
vh.empageview = (TextView) convertView.findViewById(R.id.eage);
vh.empdeptview = (TextView) convertView.findViewById(R.id.edept);
vh.empchkbox = (CheckBox) convertView.findViewById(R.id.ckekDelete);
Log.i("*null3*","*null3*");
vh.empnameview.setText(arrname.get(position));
vh.empnameview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(ShowListView.this,UpdateDB.class);
String name = arrname.get(position);
int age = Integer.parseInt(arrage.get(position));
String dept = arrdept.get(position);
int rowid = arrRowId.get(position);
intent.putExtra("KeyName" , name);
intent.putExtra("Keyage" , age);
intent.putExtra("Keydept" , dept);
intent.putExtra("Rowid", rowid);
startActivity(intent);
}
});
vh.empageview.setText(arrage.get(position));
vh.empdeptview.setText(arrdept.get(position));
vh.empchkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "OnChecked"+position, 2000).show();
if(buttonView.isChecked()){
arrDelId.add(arrRowId.get(position));
//Toast.makeText(getApplicationContext(), "OnChecked"+position, 2000).show();
// DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
// db.open();
// db.deleteEmpList(arrRowId.get(position));
// Toast.makeText(getApplicationContext(), "delet", 3000).show();
// db.close();
//
}
else{
for(int i=0;i<arrDelId.size();i++){
if(arrRowId.get(position) == arrDelId.get(i)){
arrDelId.remove(i);
}
}
}
}
});
Log.i("******", "complete");
} else {
Log.i("*not*","*not*");
vh = (ViewHolder) convertView.getTag();
}
deleteBtn = (Button) findViewById(R.id.delBtn);
deleteBtn.setOnClickListener(this);
btnadd = (Button) findViewById(R.id.addBtn);
btnadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent inte = new Intent(ShowListView.this, MainActivity.class);
startActivity(inte);
}
});
// imageView.setImageResource(thumbarr[position]);
return convertView;
}
public View getView1(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i=0;i<arrDelId.size();i++){
//Toast.makeText(getApplicationContext(), "OnDeleteClick "+i, 2000).show();
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
db.deleteEmpList(arrDelId.get(i));
//Toast.makeText(getApplicationContext(), "delet", 3000).show();
db.close();
}
ToGetCursorValues();
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
}
}
}
3. for update
package com.db;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateDB extends Activity implements OnClickListener{
Intent intnt;
EditText editname,editage,editdept;
Button updateBtn;
int row_id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editname = (EditText) findViewById(R.id.empname);
editage = (EditText) findViewById(R.id.empage);
editdept = (EditText) findViewById(R.id.empdpt);
updateBtn = (Button) findViewById(R.id.btnSubmit);
updateBtn.setText("Update");
intnt = getIntent();
editname.setText(intnt.getStringExtra("KeyName"));
editage.setText(""+intnt.getIntExtra("Keyage",0));
editdept.setText(intnt.getStringExtra("Keydept"));
row_id = intnt.getIntExtra("Rowid", 0);
updateBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "update", 3000).show();
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
String empname = editname.getText().toString();
int empage = Integer.parseInt(editage.getText().toString());
String empdept = editdept.getText().toString();
//db.deleteEmpList(row_id);
db.updateEmplist(empname, empage, empdept,row_id);
//Toast.makeText(getApplicationContext(), "delet", 3000).show();
db.close();
Intent list = new Intent(UpdateDB.this,ShowListView.class);
startActivity(list);
}
});
// Toast.makeText(getApplicationContext(), "update "+intnt.getIntExtra("Keyage",0), 3000).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}

Resources