Calling Class to another activity - java

I have a second activity that handles all the user input and another activity that handles all the data from the second activity. What I want to do is call a class "SubmitName" from the activity to the second activity so that I dont need to pass the values from second activity to the main activity anymore. Here are the codes..
MainActivity (Where the class "SubmitName" are located and values are passed.)
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView Name;
String lastname;
String licensenumber;
String mviolation;
String maplace;
String maddress;
String phonenumber;
String officername;
String contactnumber;
String datetime;
RecyclerView.LayoutManager layoutManager;
RecyclerAdapter adapter;
ArrayList<Violator> arrayList = new ArrayList<>();
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBtn = (Button)findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FragActivity.class);
startActivity(intent);
}
});
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
Name = (TextView) findViewById(R.id.tvName);
Intent intent = getIntent();
String str = intent.getStringExtra("firstname");
lastname = intent.getStringExtra("lastname");
licensenumber = intent.getStringExtra("licensenumber");
mviolation = intent.getStringExtra("violation");
maplace = intent.getStringExtra("arrestplace");
maddress = intent.getStringExtra("address");
phonenumber = intent.getStringExtra("phonenumber");
contactnumber = intent.getStringExtra("contactnumber");
officername = intent.getStringExtra("officername");
datetime = intent.getStringExtra("datetime");
Name.setText(str);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
readFromLocalStorage();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
readFromLocalStorage();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.TrafficAd:
Intent i = new Intent(this, TrafficAdvisory.class);
this.startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
public void submitName(View view)
{
String name = Name.getText().toString();
String lname = lastname;
String lnumber = licensenumber;
String violation = mviolation;
String aplace = maplace;
String address = maddress;
String pnumber = phonenumber;
String cnumber = contactnumber;
String oname = officername;
String dtime = datetime;
saveToAppServer(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime);
Name.setText("");
}
public void readFromLocalStorage()
{
arrayList.clear();
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = dbHelper.readFromLocalDatabase(database);
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
String lname = cursor.getString(cursor.getColumnIndex(DBContract.LNAME));
String lnumber = cursor.getString(cursor.getColumnIndex(DBContract.LNUMBER));
String violation = cursor.getString(cursor.getColumnIndex(DBContract.VIOLATION));
String aplace = cursor.getString(cursor.getColumnIndex(DBContract.ARRESTPLACE));
String address = cursor.getString(cursor.getColumnIndex(DBContract.ADDRESS));
String pnumber = cursor.getString(cursor.getColumnIndex(DBContract.PNUMBER));
String cnumber = cursor.getString(cursor.getColumnIndex(DBContract.CNUMBER));
String oname = cursor.getString(cursor.getColumnIndex(DBContract.ONAME));
String dtime = cursor.getString(cursor.getColumnIndex(DBContract.DTIME));
int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
arrayList.add(new Violator(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,sync_status));
}
adapter.notifyDataSetChanged();
cursor.close();
}
public void saveToAppServer(final String name,final String lname, final String lnumber,final String violation, final String aplace,final String address, final String pnumber, final String cnumber, final String oname, final String dtime)
{
if (checkNetworkConnection())
{
StringRequest stringRequest = new StringRequest(Request.Method.POST,DBContract.SERVER_URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if(Response.equals("OK"))
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_OK);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
} catch (JSONException e){
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name",name);
params.put("lname",lname);
params.put("lnumber",lnumber);
params.put("violation", violation);
params.put("aplace", aplace);
params.put("address",address);
params.put("pnumber",pnumber);
params.put("cnumber",cnumber);
params.put("oname",oname);
params.put("dtime",dtime);
return params;
}
}
;
MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
}
SecondActivity (Where inputs are handled and data passing to the mainactivity)
public class ViolatorDetail extends AppCompatActivity implements View.OnClickListener{
EditText Name;
Button btnClose;
TextView DTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violator_detail);
DTime = (TextView)findViewById(R.id.tvDTime);
final String currentDT = DateFormat.getDateTimeInstance().format(new Date());
DTime.setText(currentDT);
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(this);
Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText Name = (EditText)findViewById(R.id.etfName);
EditText LName = (EditText)findViewById(R.id.etlName);
EditText LNumber = (EditText)findViewById(R.id.etlNumber);
EditText Violation = (EditText)findViewById(R.id.etViolation);
EditText Arrestplace = (EditText)findViewById(R.id.etaPlace);
EditText Address = (EditText)findViewById(R.id.etAddress);
EditText PNumber = (EditText)findViewById(R.id.etpNumber);
EditText CNumber = (EditText)findViewById(R.id.etcNumber);
EditText OName = (EditText)findViewById(R.id.etoName);
String DT = DTime.getText().toString();
Intent intent = new Intent(ViolatorDetail.this, MainActivity.class);
intent.putExtra("firstname", Name.getText().toString());
intent.putExtra("lastname", LName.getText().toString());
intent.putExtra("licensenumber", LNumber.getText().toString());
intent.putExtra("violation", Violation.getText().toString());
intent.putExtra("arrestplace", Arrestplace.getText().toString());
intent.putExtra("address", Address.getText().toString());
intent.putExtra("phonenumber", PNumber.getText().toString());
intent.putExtra("contactnumber", CNumber.getText().toString());
intent.putExtra("officername", OName.getText().toString());
intent.putExtra("datetime", DT);
startActivity(intent);
}
});
}
}
What I want to do is call the "SUBMITNAME" class to the second activity so that no data passing will be done anymore.

As other friends mentioned Intent is a correct and good way to transfer data between activities. But if you want to avoid writing so much code to transfer data I suggest to create a pure java class (or java bean) and define all needed fields in that class (note: this class should implement java.io.Serializable interface). Now you could transfer instances of this class between activities.

I don’t think there is a better way of passing data between activities than Intents.
What you probably need is encapsulation of passing of extra. You can achieve this by making a static method in the ViolatorDetail class, which accepts as arguments as values you would like to pass, and returns Intent.
public static Intent newIntent(Context packageContext, String ... args){
Intent intent = new Intent(packageContext, ViolatorDetail.this);
intent.putExtra(EXTRA_STRING_ARGS, args);
return intent;
}
Then in the caller class you make an intent by makeing a static call on that function, and pass values as arguments
Intent intent = ViolatorDetail.newIntent(getActivity(), strings)
startActivity(intent);
However, in your case, you should probably make a more sensible way of passing data than as array of strings.

If you don't want to pass data between Activities with Intent, you can do it by writing certain data in a file and when you need it just read from it... I did it like this and I'm still happy i did it that way, it's simple and relatively quick, you just have to care a little about IOExceptions.

Related

How can I get the date from MaterialDatePicker?

My application uses MaterialDatePicker. I want to create a class that, among other data, will store the date from the MaterialDatePicker.
I have some questions:
What is the best way to save the date in the class if it is supposed to be changeable?
How to get the date from the date picker material for this?
Here's my activity where I'm using the date picker material. By clicking on the checkbox, I want to save all this information, including the date, into a class object.
Here is my code of activity with MaterialDatePicker
public class NewEvent extends AppCompatActivity {
TextInputEditText etDate, etEventId;
AutoCompleteTextView etType, etNotif;
MaterialToolbar toolbarNE;
SharedPreferences sharedPreferences;
private static final String TAG = "myLogs";
static final String newEv = "newEv";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_event);
final FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
final FirstFragment fragment1 = new FirstFragment();
etDate = findViewById(R.id.etDate);
etType = findViewById(R.id.etType);
etNotif = findViewById(R.id.etNotif);
etEventId = findViewById(R.id.etEventId);
toolbarNE = findViewById(R.id.menuNewEvent);
toolbarNE.setOnMenuItemClickListener(new MaterialToolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId())
{
case R.id.applyEvent:
/*Bundle bundle = new Bundle();
bundle.putString("name", (String) etEventId.getText().toString());
fragment1.setArguments(bundle);
fragmentTransaction.replace(R.id.q3, fragment1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();*/
Intent intent = new Intent(NewEvent.this, FirstFragment.class);
intent.putExtra("name", (String) etEventId.getText().toString());
setResult(RESULT_OK, intent);
finish();
//Toast.makeText(getApplicationContext(), materialDatePicker.getHeaderText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
// MaterialDatePicker stuff
MaterialDatePicker.Builder builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText("Выберите дату");
final MaterialDatePicker materialDatePicker = builder.build();
etDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(), "DATE_PICKER");
}
});
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
etDate.setText(materialDatePicker.getHeaderText());
}
});
// Тип события
List listEvent = new ArrayList();
Collections.addAll(listEvent, "Material", "Shit");
ArrayAdapter adapterEvent = new ArrayAdapter(this,R.layout.list_item,listEvent);
etType.setAdapter(adapterEvent);
// Тип уведомления
List listNotif = new ArrayList();
//items.add("Material");
//items.add("Shit");
Collections.addAll(listNotif, "Каждый день", "Раз в 2 дня", "Раз в 3 дня", "Раз в 5 дней", "Раз в неделю", "Не напоминать");
//String [] ITEMS = new String[] {"S1", "S2", "S3"};
//ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.list_item, ITEMS);
ArrayAdapter adapterNotif = new ArrayAdapter(this,R.layout.list_item, listNotif);
etNotif.setAdapter(adapterNotif);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
Here is my code for the future class, but there is nothing in it yet, because I was thinking about the date.
public class Event {
public String Name;
public String Date; // I don't know what type of variable to specify here, so far I have specified a string.
public String Comment;
public String Type;
public String Notify;
Event()
{
Name = "Событие";
Date = "Date";
Comment = "Comment";
Type = "Type";
Notify = "Notify";
}
}
To get the date use:
MaterialDatePicker<Long> picker = builder.build();
picker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Long>() {
#Override public void onPositiveButtonClick(Long selection) {
// Do something...
}
});
In this way you have the selected date as milliseconds.
If you want to format as a String you can use something like:
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
utc.setTimeInMillis(selection);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format.format(utc.getTime());

Want to Implements View.OnItemClickListener

i want to implements this method into my coding,but i dont know how to do it,can someone give me some suggestion on how to do it?
Below is the screenshot the coding that i want to use.
View.ONItemClickListener
this is my coding.
ViewOrder.java
public class ViewOrder extends AppCompatActivity implements ListView.OnItemClickListener {
public static final String JSON_URL = "http://dashberry.com/strack/mobile/viewOrder.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_order);
listView = (ListView) findViewById(R.id.listView);
sendRequest();
}
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL, new Response.Listener<String>() {
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ViewOrder.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.itemName,ParseJSON.origin,ParseJSON.destination);
listView.setAdapter(cl);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ItemDetail.class);
//ParseJSON<String> map = (ParseJSON)parent.getItemAtPosition(position);
//HashMap<String,String> map = (HashMap)parent.getItemAtPosition(position);
// String empId = map.get(ParseJSON.itemName).toString();
// intent.putExtra("item_id", empId);
startActivity(intent);
}
}
ParseJSON.java
public class ParseJSON {
public static String[] itemName;
public static String[] origin;
public static String[] destination;
public static final String JSON_ARRAY = "result";
public static final String KEY_NAME = "itemName";
public static final String KEY_ORIGIN = "origin";
public static final String KEY_DESTINATION = "destination";
private JSONArray users = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
itemName = new String[users.length()];
origin = new String[users.length()];
destination = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
itemName[i] = jo.getString(KEY_NAME);
origin[i] = jo.getString(KEY_ORIGIN);
destination[i] = jo.getString(KEY_DESTINATION);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So basically what i want is when user click the item in the list,it will take the user to the next activity with some data(itemName).
implement onItemClick like
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
//start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, ItemDetail.class);
//you can putExtra only position or id
intent.putExtra("position", position);
intent.putExtra("id", id);
startActivity(intent);
}
You Should Create Anther Activity called ItemDetail you can get id and position by add this code in onCreate() to know which item was clicked
Intent intent = getIntent();
String position = intent.getStringExtra("position");
String id = intent.getStringExtra("id");

Retrieving data from wrong database

I have two SQLiteDatabases in my application. One retrieves the user's input from the class DataEntryHome. The other retrieves the user's input from the class GarmentEntry. I also have two activities which display the user's inputs in the form of a ListView. These are shown in the activities RecapPage and RecapOrderDetails.
To make things simpler for myself as a new java programmer, I have used separate dbHelper, DataProvider and ListDataAdapter classes for the separate databases.
My issue is that in the RecapOrderDetails class, the ListView is populated with the contents from DataEntryHome rather than from GarmentEntry. The ListView in RecapPage works as it should.
Here is all of the code that I think is relevant:
DataEntryHome:
public class DataEntryHome extends AppCompatActivity implements TextWatcher{
private static Button DataEntryButtonN, SaveDataButton, PreviewButton;
Context context = this;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
EditText ContactName,ContactSurname,ContactEmail,ContactPhone,ContactAddInfo;
Button saveDetails;
public static ArrayList<String> CUSTOMERS = new ArrayList<String>();
String customers[];
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
final EditText surnameArray = (EditText) findViewById(R.id.customerSurnameEntry);
saveDetails = (Button) findViewById(R.id.saveDetailsButton);
saveDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=surnameArray.getText().toString().trim();
if(erm.length() != 0){
CUSTOMERS.add(erm);
surnameArray.setText("");
}
Intent arrayItems = new Intent(DataEntryHome.this, RecapPage.class);
Bundle arrayItemsBundle = new Bundle();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_entry_home);
ContactName = (EditText) findViewById(R.id.customerFirstNameEntry);
ContactName.addTextChangedListener(this);
ContactSurname = (EditText) findViewById(R.id.customerSurnameEntry);
ContactSurname.addTextChangedListener(this);
ContactEmail = (EditText) findViewById(R.id.customerEmail);
ContactEmail.addTextChangedListener(this);
ContactPhone = (EditText) findViewById(R.id.customerNumber);
ContactPhone.addTextChangedListener(this);
ContactAddInfo = (EditText) findViewById(R.id.addInfo1);
setupSaveDataButton();
}
public void addContact(View view) {
String name = ContactName.getText().toString();
String surname = ContactSurname.getText().toString();
String email = ContactEmail.getText().toString();
String phone = ContactPhone.getText().toString();
String add_info = ContactAddInfo.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformation(name,surname,email,phone,add_info,sqLiteDatabase);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelper.close();
}
RecapPage:
public class RecapPage extends AppCompatActivity{
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
GarmentEntry:
public class GarmentEntry extends AppCompatActivity {
Spinner tcshenspinner, backprintoptionsspinner, tcbackhenspinner, cosspinner, ppspinner;
ArrayAdapter<CharSequence> tcshenspinneradapter, backprintoptionsspinneradapter, tcbackhenspinneradapter,
cosspinneradapter, ppspinneradapter;
Button nextButton1;
public static ImageView imagePreview;
public static final String IMAGE_RES_ID_1 = "image_res_id_1";
Context contextOrder = this;
OrderDbHelper userDbHelperOrder;
SQLiteDatabase sqLiteDatabaseOrder;
EditText OrderNoOfShirts, OrderFrontText,OrderShirt1;
Spinner OrderColourOfShirts, OrderPrintPosition, OrderColourOfText, OrderBackPrint, OrderBackColour;
Button saveOrderDetails;
public static ArrayList<String> ORDERINFO = new ArrayList<>();
String orderinfo[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.garment_entry);
final EditText shirtArray = (EditText)findViewById(R.id.noofshirts);
saveOrderDetails = (Button)findViewById(R.id.saveOrderDetails);
saveOrderDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=shirtArray.getText().toString().trim();
if (erm.length() != 0){
ORDERINFO.add(erm);
shirtArray.setText("");
}
Intent arrayItemsOrder = new Intent(GarmentEntry.this, RecapOrderDetails.class);
Bundle arrayItemsOrderBundle = new Bundle();
}
});
OrderNoOfShirts = (EditText)findViewById(R.id.noofshirts);
OrderColourOfShirts = (Spinner)findViewById(R.id.cosspinner);
OrderFrontText = (EditText)findViewById(R.id.fronttexthint);
OrderPrintPosition = (Spinner)findViewById(R.id.ppspinner);
OrderColourOfText = (Spinner)findViewById(R.id.tcshenspinner);
OrderBackPrint = (Spinner)findViewById(R.id.backprintoptionsspinner);
OrderBackColour = (Spinner)findViewById(R.id.tcbackhenspinner);
OrderShirt1 = (EditText)findViewById(R.id.nnsshirt1);
}
public void addOrder(View view){
String no_of_shirts = OrderNoOfShirts.getText().toString();
String colour_of_shirts = OrderColourOfShirts.getSelectedItem().toString();
String front_text = OrderFrontText.getText().toString();
String print_position = OrderPrintPosition.getSelectedItem().toString();
String colour_of_text = OrderColourOfText.getSelectedItem().toString();
String back_print = OrderBackPrint.getSelectedItem().toString();
String back_colour = OrderBackColour.getSelectedItem().toString();
String shirt_1 = OrderShirt1.getText().toString();
userDbHelperOrder = new OrderDbHelper(contextOrder);
sqLiteDatabaseOrder = userDbHelperOrder.getWritableDatabase();
userDbHelperOrder.addInformationOrder(no_of_shirts,colour_of_shirts,front_text,print_position,colour_of_text,back_print,
back_colour,shirt_1, null,null,null,null,null,null,null,null,null,null,sqLiteDatabaseOrder);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelperOrder.close();
}
RecapOrderDetails:
public class RecapOrderDetails extends AppCompatActivity {
ListView listViewOrder;
SQLiteDatabase sqLiteDatabaseOrder;
UserDbHelper userDbHelperOrder;
Cursor cursorOrder;
ListDataAdapterOrder listDataAdapterOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_order_details);
listViewOrder = (ListView)findViewById(R.id.list_view_order);
listViewOrder.setClickable(true);
listDataAdapterOrder = new ListDataAdapterOrder(getApplicationContext(),R.layout.order_layout);
listViewOrder.setAdapter(listDataAdapterOrder);
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
}while (cursorOrder.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
I THINK the reason why the wrong data is being passed into the second database is because of this:
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
Are the values 0-4 reserved for the first database (for DataEntryHome)?
I also think that this:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
has something to do with the matter.
I have figured it out.
On activity RecapOrderDetails, This:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
was this issue.
To resolve it, I had to do the following:
OrderDbHelper = orderDbHelperOrder
in the main method.
And then replace
userDbHelperOrder = new UserDbHelper(getApplicationContext());
with
orderDbHelperOrder = new OrderDbHelper(getApplicationContext());

My app is force closing when clicking on button to switch to another activity. here i am putting my code

i am trying json parsing from url by replacing registration no, DOB, roll no by user. but when i click on submit button to switch to result activity. its stops working
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String Regno;
private String Rollno;
private String Dob;
private EditText regno;
private EditText rollno;
private EditText dob;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
regno=(EditText)findViewById(R.id.Registrationid);
rollno=(EditText)findViewById(R.id.Rollno);
dob=(EditText)findViewById(R.id.Dob);
Button submit =(Button)findViewById(R.id.Submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regno=regno.getText().toString();
Rollno=rollno.getText().toString();
Dob=dob.getText().toString();
Intent i= new Intent(MainActivity.this, Resultview.class);
startActivity(i);
i.putExtra("Regno",Regno);
i.putExtra("Rollno",Rollno);
i.putExtra("Dob",Dob);
}
});
}
}
ResultActivity.java
public class Resultview extends AppCompatActivity {
Intent intent= getIntent();
String Regno = intent.getExtras().getString("Regno");
String Rollno = intent.getExtras().getString("Rollno");
String Dob = intent.getExtras().getString("Dob");
private final String url ="http://example.ubs.in/utpn/api/mobileroll/enquiry/"+Rollno+"/"+Regno+"/"+Dob+"/mobileapi";
private static final String TAG_NAME="name";
private static final String TAG_ROLL="roll";
private static final String TAG_REGNO="regno";
JSONArray result=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resultview);
ServiceHandler sh = new ServiceHandler();
JSONObject json = sh.getJSONFromUrl(url);
try {
result=json.getJSONArray(TAG_NAME);
for (int i = 0; i < result.length(); i++) {
JSONObject r = result.getJSONObject(i);
String name = r.getString(TAG_NAME);
TextView nameset=(TextView)findViewById(R.id.nameset);
nameset.setText( name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the problem:
...
startActivity(i);
i.putExtra("Regno",Regno);
i.putExtra("Rollno",Rollno);
i.putExtra("Dob",Dob);
once you start the activity is to late to put extras...

TimePicker Saves Zero Value in SQLite Database

I have a TimePicker which I'd like to use to determine a length of time a user can stay connected. Lets say the time now is 10:00 if the user selects 11:00 - I'd like the source code below to determine that there are 60 minutes between the current time - and the time selected and set that to a string/long (minutes) which I then have displayed as a textview.
I've coded everything as I thought it should be - however the textview never seems to update with minutes value. Everytime I attempt to view the data - I get a value of 0 not matter what the timepicker is set to.
Anyone have any suggestions? I'm stumped at the moment and I'm not sure what else to try.
ADDEDITDEVICE.JAVA (where the timepicker and minutes determination takes place)
public class AddEditDevice extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TextView ssidTextView;
Date date = new Date();
TimePicker tp;
// #Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssidString = info.getSSID();
if (ssidString.startsWith("\"") && ssidString.endsWith("\"")){
ssidString = ssidString.substring(1, ssidString.length()-1);
//TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssidString);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
date.setMinutes(tp.getCurrentMinute());
date.setHours(tp.getCurrentHour());
Long.toString(minutes);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditDevice.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});}
}
long minutes = ((new Date()).getTime() - date.getTime()) / (1000 * 60);
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
// Log.i("Test for Null", ""+dbConnector+" "+nameEt+" "+capEt+" "+timeEt+" "+codeEt+" "+ssidTextView);
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
}
}
VIEW COUNTRY.JAVA (where the minutes data set by the timepicker should be visible)
public class ViewCountry extends NfcBeamWriterActivity {
private static final String TAG = ViewCountry.class.getName();
protected Message message;
NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView timeTv;
private TextView ssidTv;
private TextView combined;
private TextView minutes;
//String timetest = "300";
// String a="\"";
// String b="\"";
// String message1 = a + ssidTv.getText().toString() +"," +
// capTv.getText().toString()+b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("name", true);
editor.putBoolean("cap", true);
editor.putBoolean("code", true);
editor.putBoolean("time", true);
editor.putBoolean("ssid",true);
editor.putBoolean("minutes",true);
editor.putBoolean("timetest",true);
editor.commit();
setDetecting(true);
startPushing();
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
timeTv = (TextView) findViewById(R.id.timeEdit);
codeTv = (TextView) findViewById(R.id.codeText);
ssidTv = (TextView) findViewById(R.id.wifiSSID);
minutes = (TextView) findViewById(R.id.Minutes);
}
#Override
protected void onResume() {
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params) {
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result) {
super.onPostExecute(result);
result.moveToFirst();
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int timeIndex = result.getColumnIndex("time");
int ssidIndex = result.getColumnIndex("ssid");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
timeTv.setText(result.getString(timeIndex));
codeTv.setText(result.getString(codeIndex));
ssidTv.setText(result.getString(ssidIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editItem:
Intent addEditContact = new Intent(this, AddEditDevice.class);
// addEditContact.putExtra(CountryList.ROW_ID, rowID);
// addEditContact.putExtra("name", nameTv.getText());
// addEditContact.putExtra("cap", capTv.getText());
// addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.user1SettingsSave:
Intent Tap = new Intent(this, Tap.class);
startActivity(Tap);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact() {
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DatabaseConnector dbConnector = new DatabaseConnector(
ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
#Override
protected Object doInBackground(Long... params) {
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":" + timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
minutes,
Long.toString(minutes),
ssidTextView.getText().toString());
You have that code to add a contact, BUT in your database conector you have:
public void insertContact(String name,
String cap,
String code,
String time,
long minutes,
String ssid,
String string){
I think that don't match, so this is why don't insert correctly.
BTW i can't comment at the moment because i need 50 reputation.
Regards
USE CREATE TABLE IF NOT EXISTS T/N then your problem wil be solved.
otherwise it will override the current table at the same time all the data will be lost.

Categories