Confuse about android check list box - android

I would like to implement products list with checklistbox after select radio button.
And I would like to show chekclistbox as dialog box. My product list data come from sqllite.
It is need to implement adapter class to show data for checklistbox or can I directly implement for checklistbox data in alertDialog . Please clear for me.
In mainActivity
public RadioGroup.OnCheckedChangeListener setOnCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rdoPCode = (RadioButton) findViewById(checkedId);
switch (checkedId) {
case R.id.rdoAll:
Toast.makeText(context, rdoPCode.getText(), Toast.LENGTH_SHORT)
.show();
break;
case R.id.rdoCustom:
Intent localIntent = new Intent(MainActivity.context,
ProductListChkActivity.class);
MainActivity.context.startActivity(localIntent);
break;
}
}
};
In ProductListChkActivity
public class ProductListChkActivity extends Activity {
private static Button button_selectall;
private static Button button_unselectall;
private static CheckBox chkProductCode;
private static CashSaleProductLogic _sellProductLogic;
public static List<CashSaleProductInfo> _SaleProductInfo;
public static ListView lvlchkPrdlist;
private Button btnSelectAll, btnUnSelectAll;
// For chk productcode
private static ProductListChkAdapter _ProductListChkAdapter;
Context context;
#Override
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.productinofchk);
context = this;
init();
ProductCodeChk();
}
private void init() {
button_selectall = (Button) this.findViewById(R.id.button_selectall);
button_unselectall = (Button) this
.findViewById(R.id.button_unselectall);
chkProductCode = (CheckBox) this.findViewById(R.id.chkProductCode);
lvlchkPrdlist = (ListView) this.findViewById(R.id.lvlchkPrdlist);
_sellProductLogic = new CashSaleProductLogic(this);
_SaleProductInfo = _sellProductLogic.getAllsellProductDataLogic();
}
protected void ProductCodeChk() {
try {
_ProductListChkAdapter = new ProductListChkAdapter(context,
_SaleProductInfo, 1);
this.lvlchkPrdlist.setAdapter(_ProductListChkAdapter);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public void OnClickbillbtncancel(View paramView) {
MainActivity.textClear();
Intent localIntent = new Intent(ProductListChkActivity.this,
MainActivity.class);
ProductListChkActivity.this.startActivity(localIntent);
}
}
I would like to show productinofchk layout as dialogbox

You need to go through floating dialogs in android. check out this documentation :
link

Related

Why can't function "if (counter >10)" work?

I'm trying to get an AlertDialog to appear if my counter is above 10.
I have tried using the TextView variable peopleCount in the if statement but it does not work too. I know using TextView will not work but I need to know if there is a workaround.
private TextView peopleCount;
private ImageView plusOne;
private ImageView minusOne;
private ImageView reset;
private int counter;
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.ivPlusOne :
plusCounter();
break;
case R.id.ivMinusOne :
minusCounter();
break;
case R.id.ivReset :
initCounter();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people);
peopleCount = (TextView)findViewById(R.id.tvPeopleCount);
plusOne = (ImageView)findViewById(R.id.ivPlusOne);
plusOne.setOnClickListener(clickListener);
minusOne = (ImageView)findViewById(R.id.ivMinusOne);
minusOne.setOnClickListener(clickListener);
reset = (ImageView)findViewById(R.id.ivReset);
reset.setOnClickListener(clickListener);
initCounter();
if( counter > 10) {
AlertDialog.Builder peopleAlert = new AlertDialog.Builder(PeopleActivity.this);
peopleAlert.setCancelable(false);
peopleAlert.setTitle("People Count High");
peopleAlert.setMessage("Please check and replenish inventory");
peopleAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogPeople, int which) {
dialogPeople.cancel();
}
});
peopleAlert.show();
}
private void initCounter(){
counter = 0;
peopleCount.setText(counter + "");
}
private void plusCounter(){
counter++;
peopleCount.setText(counter + "");
}
private void minusCounter(){
counter--;
peopleCount.setText(counter + "");
}
I expected the AlertDialog to appear when counter reached 11 but nothing happens.
OnCreate only runs once, You need to move the if statement to a function and call it from your plusCounter() and minusCounter() functions.

Save ArrayList of custom objects and add a new object to ArrayList

I'm having an issue with saving the instance of an ArrayList of custom objects in an Activity and then retreiving it after doing some stuff in another Activity. Inside the first Activity (which has the ArrayList), there is a button to start a second activity. Inside this second Activity the user is asked to create a new object that will be added afterwards in the ArrayList of the first Activity, so that when the second Activity finishes the first Activity is shown again with a ListView of all the objects (including the last one created). The problem I'm facing is that only the last object created is being shown in the ListView.
Here is the code of the first Activity:
public class CargasMin extends AppCompatActivity implements View.OnClickListener {
RelativeLayout rl_CargasMin;
ImageButton bt_AdDep;
Button bt_CalcCargas;
ListView listView_Dep;
ArrayList<Dependencia> listaDeDependencias = new ArrayList<Dependencia>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.min_cargas);
rl_CargasMin = (RelativeLayout) findViewById(R.id.cargasMinLayout);
bt_AdDep = (ImageButton) findViewById(R.id.bt_AdDep_CargasMin);
bt_CalcCargas = (Button) findViewById(R.id.bt_CalcCargas_CargasMin);
bt_AdDep.setOnClickListener(this);
bt_CalcCargas.setOnClickListener(this);
// This seems not to be working!
if(savedInstanceState == null) { }
else {
listaDeDependencias = savedInstanceState.getParcelableArrayList("key");
}
// Get last object created
Intent intent_de_AdDep = getIntent();
Dependencia dependenciaAAdicionar = (Dependencia) intent_de_AdDep.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar == null) { }
else {
listaDeDependencias.add(dependenciaAAdicionar);
}
//Cria Adapter pra mostrar dependencias na ListView
DependenciaAdapter adapterDeDependencias = new DependenciaAdapter(this, R.layout.adapter_dependencia, listaDeDependencias);
//Seta Adapter
listView_Dep = (ListView) findViewById(R.id.listView_Dep_CargasMin);
listView_Dep.setAdapter(adapterDeDependencias);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivity(intent_AdDep);
break;
case R.id.bt_CalcCargas_CargasMin:
//
break;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// Aqui se salva a listaDeDependencias quando a Atividade eh momentaneamente fechada.
outState.putParcelableArrayList("key", listaDeDependencias);
super.onSaveInstanceState(outState);
}
}
This is the code of my custom class Dependencia:
public class Dependencia implements Parcelable {
String nome;
int tipo;
float largura = 0;
float comprimento = 0;
float area = 0;
float perimetro = 0;
// Constructor da classe Dependencia.
public Dependencia(String nomeDep, int tipoDep) {
nome = nomeDep;
tipo = tipoDep;
}
private Dependencia(Parcel in) {
nome = in.readString();
tipo = in.readInt();
largura = in.readFloat();
comprimento = in.readFloat();
area = in.readFloat();
perimetro = in.readFloat();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(nome);
out.writeInt(tipo);
out.writeFloat(largura);
out.writeFloat(comprimento);
out.writeFloat(area);
out.writeFloat(perimetro);
}
public static final Parcelable.Creator<Dependencia> CREATOR = new Parcelable.Creator<Dependencia>() {
public Dependencia createFromParcel(Parcel in) {
return new Dependencia(in);
}
public Dependencia[] newArray(int size) {
return new Dependencia[size];
}
};
}
And this is the code of the second Activity:
public class AdDep extends AppCompatActivity implements View.OnClickListener {
RelativeLayout rl_AdDep;
EditText et_Nome;
EditText et_Largura;
EditText et_Comprimento;
EditText et_Area;
EditText et_Perimetro;
Spinner spinner_Tipo;
String vetorTipo[];
int tipoEscolhido;
Button bt_AdDep1;
Button bt_AdDep2;
Dependencia novaDependencia;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dep_ad);
rl_AdDep = (RelativeLayout)findViewById(R.id.adDepLayout);
et_Nome = (EditText) findViewById(R.id.et_Nome_AdDep);
et_Largura = (EditText) findViewById(R.id.et_Largura_AdDep);
et_Comprimento = (EditText) findViewById(R.id.et_Comprimento_AdDep);
et_Area = (EditText) findViewById(R.id.et_Area_AdDep);
et_Perimetro = (EditText) findViewById(R.id.et_Perimetro_AdDep);
spinner_Tipo = (Spinner) findViewById(R.id.spinner_Tipo_AdDep);
bt_AdDep1 = (Button) findViewById(R.id.bt_AdDep1);
bt_AdDep2 = (Button) findViewById(R.id.bt_AdDep2);
// Adicionando opcoes no spinner
vetorTipo = new String[5];
vetorTipo[0] = "Banheiro";
vetorTipo[1] = "Varanda";
vetorTipo[2] = "Cozinha/Copa/Serviço/etc.";
vetorTipo[3] = "Sala/Dormitório";
vetorTipo[4] = "Outro";
// Criando ArrayAdapter de strings pro spinner
ArrayAdapter<String> adapterTipo = new ArrayAdapter<String>(AdDep.this, android.R.layout.simple_spinner_item, vetorTipo);
// Setando o Adapter
spinner_Tipo.setAdapter(adapterTipo);
// Valor default do spinner (hint)
spinner_Tipo.setSelection(0);
bt_AdDep1.setOnClickListener(this);
bt_AdDep2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Banheiro"))
tipoEscolhido = 1;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Varanda"))
tipoEscolhido = 2;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Cozinha/Copa/Serviço/etc."))
tipoEscolhido = 3;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Sala/Dormitório"))
tipoEscolhido = 4;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Outro"))
tipoEscolhido = 5;
novaDependencia = new Dependencia(et_Nome.getText().toString(), tipoEscolhido);
switch(v.getId()) {
case R.id.bt_AdDep1:
novaDependencia.largura = Float.valueOf(et_Largura.getText().toString());
novaDependencia.comprimento = Float.valueOf(et_Comprimento.getText().toString());
break;
case R.id.bt_AdDep2:
novaDependencia.area = Float.valueOf(et_Area.getText().toString());
novaDependencia.perimetro = Float.valueOf(et_Perimetro.getText().toString());
break;
}
AlertDialog.Builder builder2 = new AlertDialog.Builder(v.getContext());
builder2.setMessage("Deseja adicionar T.U.E. nesta dependência?").setPositiveButton("Sim", dialogClickListener).setNegativeButton("Não", dialogClickListener).show();
}
// Objeto tipo dialog criado para perguntar se usario deseja inserir TUEs
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
Intent intent_NovaDep_CargasMin = new Intent(AdDep.this, CargasMin.class);
intent_NovaDep_CargasMin.putExtra("novaDependencia", novaDependencia);
startActivity(intent_NovaDep_CargasMin);
break;
}
}
};
}
If anyone knows how to solve this, please share. Thanks.
The problem is that you're starting a new instance of the CargasMin activity from AdDep activity. Your AdDep activity should just finish and return a result back to the existing instance of CargasMin activity on the back stack for you to see all the previous list data as well.
To retrieve the new list item from AdDep as a result, use startActivityForResult()
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivityForResult(intent_AdDep, ADD_DEP_REQUEST);
break;
where ADD_DEP_REQUEST is just a request code constant
public static final int ADD_DEP_REQUEST = 1;
Now, when AdDep is done collecting data, it returns the new data item as a result.
case DialogInterface.BUTTON_NEGATIVE:
Intent result = new Intent();
result.putExtra("novaDependencia", novaDependencia);
setResult(Activity.RESULT_OK, result);
finish();
break;
Your main CargasMin activity will then receive the new data item as
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADD_DEP_REQUEST) {
if (resultCode == RESULT_OK) {
// Get last object created
Dependencia dependenciaAAdicionar =
(Dependencia) data.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar != null){
listaDeDependencias.add(dependenciaAAdicionar);
// Refresh Adapter pra mostrar dependenciaAAdicionar na ListView
adapterDeDependencias.notifyDataSetChanged();
}
}
}
}
Note that listaDeDependencias and adapterDeDependencias have been changed to instance members of the activity.
Your current approach would have worked if you were persisting the data to some storage (like in a file or database) but creating a new instance of CargasMin is still not recommended because the one existing on the back stack would suffice.

Set dynamically created TextView on frame layout

I want to pass some data from one activity to another and set it in dynamically created TextView over frame layout of that activity..I'm using intent for that but at second activity the data is not getting extracted..Can any one tell me the simple way for this..
Following is my code..
Hidden.java
public class Hidden extends Activity implements OnClickListener {
Button btnnameadd, btnnameremove, btnmobileadd, btnmobileremove, btndone;
EditText etname, etmobile;
ImageView ivlogo;
private AlertDialog dialog;
private Uri mImageCaptureUri;
Intent jump;
//options for image selection
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
LinearLayout llname, llmobile, llimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hidden);
captureImageInitialization();
init();
}
private void init() {
etname=(EditText)findViewById(R.id.editTextname);
etmobile=(EditText)findViewById(R.id.editTextmobile);
btnnameadd=(Button)findViewById(R.id.buttonnameadd);
btnnameremove=(Button)findViewById(R.id.buttonnameremove);
btnmobileadd=(Button)findViewById(R.id.buttonmobileadd);
btnmobileremove=(Button)findViewById(R.id.buttonmobileremove);
btndone=(Button)findViewById(R.id.buttondone);
llname=(LinearLayout)findViewById(R.id.name);
llmobile=(LinearLayout)findViewById(R.id.mobile);
btnnameadd.setOnClickListener(this);
btnnameadd.setOnClickListener(this);
btnnameremove.setOnClickListener(this);
btnmobileadd.setOnClickListener(this);
btnmobileremove.setOnClickListener(this);
btndone.setOnClickListener(this);
}
#Override
public void onClick(View v) {
jump=new Intent(Hidden.this,Framelayout.class);
if(v.getId()==R.id.buttonnameadd)
{
String strname=etname.getText().toString();
Log.d("Log",strname);
jump.putExtra("Name",strname);
}else if(v.getId()==R.id.buttonnameremove)
{
btnnameremove.setEnabled(false);
llname.removeView(findViewById(R.id.editTextname));
}else if(v.getId()==R.id.buttonmobileadd)
{
String strmobile=etmobile.getText().toString();
Log.d("Log",strmobile);
jump.putExtra("Mobile",strmobile);
Log.d("LOG",jump.putExtra("Mobile",strmobile).toString());
}else if(v.getId()==R.id.buttonmobileremove)
{
llmobile.removeView(findViewById(R.id.editTextmobile));
}else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
}
}
FrameLayout.java
public class Framelayout extends Activity implements OnClickListener {
FrameLayout frameLayout;
Button b2,b3;
//private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_framelayout);
frameLayout = (FrameLayout)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.buttonload);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.button2){
Intent i=new Intent(Framelayout.this,Hidden.class);
startActivity(i);
}else if(v.getId()==R.id.buttonload){
Log.d("Log",getIntent().getStringExtra("Name"));
editframelayout();
}
}
private void editframelayout() {
String name=getIntent().getExtras().getString("Name");
String mobile=getIntent().getExtras().getString("Mobile");
TextView tvname=new TextView(this);
tvname.setText(name);
tvname.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvname.setGravity(Gravity.CENTER);
TextView tvmobile=new TextView(this);
tvmobile.setText(mobile);
tvmobile.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvmobile.setGravity(Gravity.CENTER);
frameLayout.addView(tvname);
frameLayout.addView(tvmobile);
}
}
You must use one of putExtra() overloaded methods of the intent instance you created to add your data.
Here is a sample:
Intent intent = new Intent(this, SignoutActivity.class); // # this parameter is the context of the caller
intent.putExtra("PARAM_TEXTBOX_TEXT", textboxText);
startActivity(intent);
Edit for the code you added, your design is very poor and doesn't accomplish what is intended.
Every time you click a Button a new instance of Intent is created. you are calling startActivity() only in single case:
else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
Now you assume that the parameters added in previous button clicks are still there, but they aren't. When you click buttondone you create a new instance of Intent with no extras at all.
You can work this around as follows:
...
else if(v.getId()==R.id.buttondone)
{
String strname = etname.getText().toString();
if (strname != null && !strname.equals(""))
{
jump.putExtra("Name",strname);
}
String strmobile = etmobile.getText().toString();
if (strmobile != null && !strmobile.equals(""))
{
jump.putExtra("Mobile",strmobile);
}
startActivity(jump);
}
It still isn't well structured, but might do the trick for you
Use getIntent().getStringExtra("Name") instead of getIntent().getExtras().getString("Name");
getIntent().getStringExtra("Name")

Passing the same object from one activity to another activity

I have a Mainactivity that contains the list of Trainings. And on each list is clicked it starts the session of the same training in whole application.
I managed to use Singleton and access that into my main activity. But onItemClick it takes to dialog box and on button click inside dialog it should take to another activity. Now I a getting error like java NullPointerException. Here is the code below;
Remember: I want same training session in second activity also.
MainActivity class;
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
currentTraining = (Training)arg0.getAdapter().getItem(arg2);
Log.i("DEBUG", currentTraining.getTitle());
CurrentTraining.getInstance().setTraining(currentTraining);
Toast.makeText(
getApplicationContext(),
"You clicked on position : " + arg2 + " and ID : "
+ currentTraining.getId(), Toast.LENGTH_LONG).show();
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(currentTraining.getTitle());
TextView description = (TextView) dialog.findViewById(R.id.textView1);
description.setText("Description: " + currentTraining.getDescription());
TextView location = (TextView) dialog.findViewById(R.id.textView2);
location.setText("Location: " + currentTraining.getLocation());
TextView date = (TextView) dialog.findViewById(R.id.textView3);
date.setText("Date: " + currentTraining.getDate());
Button back_btn = (Button) dialog.findViewById(R.id.button1);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
Button start_btn = (Button) dialog.findViewById(R.id.button2);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
TraineeActivity.class);
//intent.putExtra("trainingId", currentTraining.getId());
//intent.putExtra("title", currentTraining.getTitle().toString());
MainActivity.this.startActivity(intent);
}
});
dialog.show();
}
And in second Activity Class;
Training currentTraining;
private ListView personNamesListView;
// Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter traineeListAdapter;
private TextView TitleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trainees);
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Log.i("DEBUG", ""+currentTraining.getTitle());
TitleView = (TextView)findViewById(R.id.training_title);
TitleView.setText(currentTraining.getTitle());
Button addnew = (Button) findViewById(R.id.add_btn);
addnew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(TraineeActivity.this,
FormActivity.class);
TraineeActivity.this.startActivity(intent);
}
});
personNamesListView = (ListView) findViewById(R.id.traineeslist);
// Create a list that contains only full name of the trainee
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
protected void onResume(){
super.onResume();
traineeListAdapter = new ArrayAdapter<Trainee>(this, android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
My Singleton Class:
public class CurrentTraining {
private Training training ; //Training is my model class
private static CurrentTraining instance;
private CurrentTraining() {
}
public static CurrentTraining getInstance() {
if (instance == null)
instance = new CurrentTraining();
return instance;
}
public Training getTraining() {
return training;
}
public Training setTraining(Training training) {
return this.training = training;
}
}
In onCreate() of your second activity, you do this:
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Since currentTraining is null, this will just set the singleton variable training to null and return null.
Where are you actually setting the value of the one that the user picked?

android putextra without start activity

i need help please.
I have two activities and a db. All i want to do is when i press a button in activity A, i send the string in my editText to the activity B. In the activity B i try to insert that string in my db and display it in a listview. All works if i start the activity B in the activity A but i wont display the activity B.
Here my code:
Activity A:
public class Example extends Activity {
public final static String ID_EXTRA2="com.example.activities";
public EditText MyInputText = null;
ImageView MyButton;
TextView MyOutputText, MyInputtext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diccionary);
MyInputText = (EditText)findViewById(R.id.InputText);
MyOutputText = (TextView)findViewById(R.id.OutputText);
MyButton = (ImageView)findViewById(R.id.botonaceptar);
MyButton.setOnClickListener(MyButtonOnClickListener);
public ImageView.OnClickListener MyTranslateButtonOnClickListener = new ImageView.OnClickListener(){
public void onClick(View v) {
String InputString;
InputString = MyInputText.getText().toString();
try{
Intent d = new Intent(Example.this, Secondactivity.class);
d.putExtra(ID_EXTRA2, InputString);
//startActivity(d); <----- If i start the secondactivity, that works...
}catch (Exception e){
}
}
};
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater awesome = getMenuInflater();
awesome.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu1:
startActivity(new Intent("com.example.activities.SECONDACTIVITY"));
return true;
case R.id.menu2:
//something to do
return true;
}
return false;
}
};
Activity B:
public class Secondactivity extends Activity {
NoteAdapter2 adapter = null;
NoteHelper2 helper2 = null;
Cursor dataset_cursor2 = null;
String entriId = null;
public ListView list2;
String passedword = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
try{
list2 = (ListView)findViewById(R.id.list2);
helper2 = new NoteHelper2(this);
---->passedword = getIntent().getStringExtra(Example.ID_EXTRA2);
---->helper2.insert(passedword); //here i insert the string in my db
startManagingCursor(dataset_cursor2);
dataset_cursor2 = helper2.getAll();
adapter = new NoteAdapter2(dataset_cursor2);
list2.setAdapter(adapter);
dataset_cursor2.requery();
adapter.notifyDataSetChanged();
//this is how we know to do when a list item is clicked
list2.setOnItemClickListener(onListClick);
}
catch (Exception e){
// this is the line of code that sends a real error message to the log
Log.e("ERROR", "ERROR IN CODE" + e.toString());
//this is the line that prints out the location in the code where the error ocurred
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
helper2.close();
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
entriId = String.valueOf(id);
}
};
class NoteAdapter2 extends CursorAdapter {
NoteAdapter2(Cursor c){
super(Zhistorytranslate.this, c);
}
public void bindView(View row2, Context ctxt, Cursor c) {
NoteHolder2 holder2 = (NoteHolder2)row2.getTag();
holder2.populateFrom2(c, helper2);
}
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row2 = inflater.inflate(R.layout.row2, parent, false);
NoteHolder2 holder2 = new NoteHolder2(row2);
row2.setTag(holder2);
return (row2);
}
}
static class NoteHolder2 {
private TextView entriText = null;
NoteHolder2(View row2){
entriText = (TextView)row2.findViewById(R.id.entri);
}
void populateFrom2(Cursor c, NoteHelper2 helper2) {
entriText.setText(helper2.getEntri(c));
}
}
If I understood you correctly, you want to send data from A to B without launching B. In this case, you need to forget about Intents and consider a way to store data in your app. My suggestion is to use SharedPreferences.
Here is how you can use it:
In your Activity A, store the String:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("string_id", InputString); //InputString: from the EditText
editor.commit();
In your Activity B, you can get the value by:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String data = prefs.getString("string_id", "no id"); //no id: default value
Your question is very difficult to understand, but you seem to want to be able to add the EditText's contents into your database without starting another Activity. Simply do this in your Image's OnClickListener:
public void onClick(View v) {
NoteHelper2 helper2 = new NoteHelper2(this);
helper2.insert(MyInputText.getText().toString());
}
You should also read about Java naming convention.

Categories

Resources