My extra data doesn't appear immediately - android

In my file Reservation.java I have a function that loads LieuActivity.
So this is the function
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Reservation extends AppCompatActivity implements View.OnClickListener {
private Button end,deb,lieu,type,cherch;
private TextView type_v ;
private ImageView car;
private View division;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
end = (Button)findViewById( R.id.btn_fin );
end.setOnClickListener( this);
deb= (Button)findViewById( R.id.deb_btn);
deb.setOnClickListener( this );
lieu = (Button)findViewById( R.id.btn_local);
lieu.setOnClickListener( this );
type = (Button)findViewById( R.id.btn_type);
type.setOnClickListener( this );
cherch= (Button)findViewById( R.id.btn_cherch);
cherch.setOnClickListener( this );
division= (View)findViewById( R.id.div3);
type_v= (TextView)findViewById( R.id.type);
car= (ImageView) findViewById( R.id.pic_car);
list=(ListView)findViewById(R.id.fin_list);
ArrayAdapter<String> mAdapter= new ArrayAdapter<String>(Reservation.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.values));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 3 )
{
Intent i = new Intent(view.getContext(),Deb_FinActivity.class);
startActivityForResult(i,3);
}
}
});
list.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.deb_btn:
loadDebActivity();
break;
case R.id.btn_fin:
loadFin();
break;
case R.id.btn_local:
loadLieuActivity();
break;
case R.id.btn_type:
loadTypeActivity();
break;
case R.id.btn_cherch:
loadSearch();
break;
}
}
private void loadDebActivity()
{
startActivity(new Intent( this,Deb_FinActivity.class ) );
finish();
}
private void loadFin()
{
lieu.setVisibility( View.INVISIBLE );
type.setVisibility(View.INVISIBLE);
cherch.setVisibility(View.INVISIBLE);
car.setVisibility(View.INVISIBLE);
division.setVisibility(View.INVISIBLE);
type_v.setVisibility(View.INVISIBLE);
list.setVisibility(View.VISIBLE);
}
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
lieu.setText(getIntent().getStringExtra("mytext"));
}
private void loadTypeActivity()
{
startActivity(new Intent( this,TypeActivity.class ) );
finish();
}
private void loadSearch()
{
}
}
In my LieuActivity.java I have this code
public class LieuActivity extends AppCompatActivity {
private EditText lieuu;
private TextView local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lieu);
addListenerOnButton();
}
public void addListenerOnButton() {
local = (TextView) findViewById(R.id.position);
local.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText lieuu = (EditText)findViewById(R.id.local);
String text =lieuu.getText().toString();
Intent myIntent = new Intent(view.getContext(),Reservation.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
}
}
The problem is when I edit in my LieuActivity and go back to reservation it does not return the extra value until I click another time on the editText so I see the updated data for a second before re-going to LieuActivity and modify it another time .

Put these lines in onCreate() of Reservation activity
String text = getIntent().getStringExtra("mytext");
if (text != null) {
lieu.setText(text);
}
and make this change:
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
finish();
}

Do this in oncreate of Reservation
Bundle extras = getIntent().getExtras();
String string;
if (extras != null) {
string = extras.getString("mytext");
lieu.setText(string);
}

Make changes like this in LieuActivity :-
public class LieuActivity extends AppCompatActivity {
private EditText lieuu;
private TextView local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lieu);
addListenerOnButton();
}
public void addListenerOnButton() {
local = (TextView) findViewById(R.id.position);
local.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText lieuu = (EditText)findViewById(R.id.local);
String text =lieuu.getText().toString();
Intent myIntent = new Intent(view.getContext(),Reservation.class);
myIntent.putExtra("mytext",text);
setResult(RESULT_OK, myIntent );
});
}
}
In Reservation put onActivityResult()
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Reservation extends AppCompatActivity implements View.OnClickListener {
private Button end,deb,lieu,type,cherch;
private TextView type_v ;
private ImageView car;
private View division;
private ListView list;
String mNewText="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
end = (Button)findViewById( R.id.btn_fin );
end.setOnClickListener( this);
deb= (Button)findViewById( R.id.deb_btn);
deb.setOnClickListener( this );
lieu = (Button)findViewById( R.id.btn_local);
lieu.setOnClickListener( this );
type = (Button)findViewById( R.id.btn_type);
type.setOnClickListener( this );
cherch= (Button)findViewById( R.id.btn_cherch);
cherch.setOnClickListener( this );
division= (View)findViewById( R.id.div3);
type_v= (TextView)findViewById( R.id.type);
car= (ImageView) findViewById( R.id.pic_car);
list=(ListView)findViewById(R.id.fin_list);
ArrayAdapter<String> mAdapter= new ArrayAdapter<String>(Reservation.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.values));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 3 )
{
Intent i = new Intent(view.getContext(),Deb_FinActivity.class);
startActivityForResult(i,3);
}
}
});
list.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.deb_btn:
loadDebActivity();
break;
case R.id.btn_fin:
loadFin();
break;
case R.id.btn_local:
loadLieuActivity();
break;
case R.id.btn_type:
loadTypeActivity();
break;
case R.id.btn_cherch:
loadSearch();
break;
}
}
private void loadDebActivity()
{
startActivity(new Intent( this,Deb_FinActivity.class ) );
finish();
}
private void loadFin()
{
lieu.setVisibility( View.INVISIBLE );
type.setVisibility(View.INVISIBLE);
cherch.setVisibility(View.INVISIBLE);
car.setVisibility(View.INVISIBLE);
division.setVisibility(View.INVISIBLE);
type_v.setVisibility(View.INVISIBLE);
list.setVisibility(View.VISIBLE);
}
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
lieu.setText(mNewText);
}
private void loadTypeActivity()
{
startActivity(new Intent( this,TypeActivity.class ) );
finish();
}
private void loadSearch()
{
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == QUEUE_MSG) {
if (resultCode == RESULT_OK) {
Serializable myText= data.getSerializableExtra("mytext");
if (myText!= null)
mNewText= myText;
}
}
}
}
Hope this may help you

Related

Accessing another activity's method

I have a medicine_activity class
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Medicine_Activity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "Medicine_Activity";
private Button btnAdd;
private ListView listMeds;
private AppDatabase db;
private ArrayAdapter<MedicineRecord> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
listMeds = findViewById(R.id.listMeds);
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
db = AppDatabase.getInstance(getApplicationContext());
FeedAdapter feedAdapter = new FeedAdapter(Medicine_Activity.this, R.layout.list_record, db.medicineRecordDao().loadAllRecords());
listMeds.setAdapter(feedAdapter);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MedicineInputActivity.class);
startActivity(intent);
}
}
In this i am trying to call update() method of another activity namely MedicineInputActivity
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MedicineInputActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MedicineInputActivity";
static EditText dosage;
static EditText medName;
static TimePicker timePicker;
static Button btnSave;
Button btnInc;
Button btnDec;
private AppDatabase db;
private static MedicineInputActivity instance;
boolean isEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_input);
isEdit = false;
instance = this;
dosage = findViewById(R.id.dosage);
dosage.setShowSoftInputOnFocus(false);
dosage.setCursorVisible(false);
medName = findViewById(R.id.medName);
timePicker = findViewById(R.id.simpleTimePicker);
btnInc = findViewById(R.id.btnInc);
btnDec = findViewById(R.id.btnDec);
btnInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
tempVal++;
dosage.setText("" + tempVal);
}
});
btnDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
if (tempVal > 0) {
tempVal--;
}
dosage.setText("" + tempVal);
}
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
db = AppDatabase.getInstance(getApplicationContext());
}
#Override
public void onClick(View v) {
String name = medName.getText().toString();
int min = timePicker.getMinute();
int hour = timePicker.getHour();
String val = dosage.getText().toString();
int dose = Integer.parseInt(val);
MedicineRecord medicineRecord = new MedicineRecord(name, dose, min, hour);
if (validate(name)) {
if (isEdit) {
db.medicineRecordDao().updateRecord(medicineRecord);
} else {
db.medicineRecordDao().insertRecord(medicineRecord);
}
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Medicine name cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean validate(String name) {
if (name.length() == 0) {
return false;
} else {
return true;
}
}
public static MedicineInputActivity getInstance() {
return instance;
}
public void update(MedicineRecord medicineRecord, boolean isEdit) {
this.isEdit = isEdit;
dosage.setText(medicineRecord.getDosage());
medName.setText(medicineRecord.getMedName());
timePicker.setHour(medicineRecord.getHour());
timePicker.setMinute(medicineRecord.getMinute());
}
}
What i am trying to achieve is when the user taps the list item, the input activity is loaded and the user can update the record. I wasnt able to find an elegant solution other than making an update method in MedicineInputActivity and then getting an instance of MedicineInputActivity in Medicine_Activity and calling update.
I am getting errors like "Attempt to invoke virtual method 'void com.example.shubhmgajra.medikit.MedicineInputActivity.update() on a null object reference".
You can return data from second activity to the first activity when user is done updating the record. You should start second activity by calling startActivityForResult() instead of startActivity() in the first activity. You should also override onActivityResult() in the first activity. You can read more here.
UPDATE:
I think you want to send selected medicine details from Medicine_Activity to MedicineInputActivity. In that case, you can send selected medicine object by binding it to the intent as follows:
public class Medicine_Activity ... {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
intent.putExtra("selectedMedicine", medicineRecord);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
...
}
}
Then on MedicineInputActivity, you should be doing this:
public class MedicineInputActivity ... {
MedicineRecord selectedMedicineRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
selectedMedicineRecord = (MedicineRecord) getIntent().getParcelableExtra("selectedMedicine");
...
}
}
To be able to do this, your MedicineRecord class should implement Parcelable interface.

java.lang.ClassCastException: com.example.harshitbahri.expensebook.MainActivity cannot be cast to com.example.harshitbahri.expensebook.EditorActivity

I want to change the TextView of editor activity by clicking on Button buttonExpense which should also open editor activity and show value of the result in
EditText mAmountEditText.
I am getting java.lang.ClassCastException in which it is clearly written that MainActivity cannot be cast to EditorActivity
Calculator.java
package com.example.harshitbahri.expensebook;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends android.support.v4.app.Fragment {
Button button0;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Button button8;
Button button9;
Button buttonAdd;
Button buttonSubstract;
Button buttonMul;
Button buttonDiv;
Button buttonClear;
Button buttonEqual;
Button buttonExpense;
String result;
String tmp;
String operator;
TextView resultTextView;
FragmentActivity fa2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fa2 = (FragmentActivity) super.getActivity();
final View RootView= inflater.inflate(R.layout.activity_calculator, container, false);
button0 = (Button)RootView.findViewById(R.id.button0);
button1 = (Button)RootView.findViewById(R.id.button1);
......
buttonAdd = (Button)RootView.findViewById(R.id.buttonAdd);
buttonClear = (Button)RootView.findViewById(R.id.buttonClear);
buttonSubstract = (Button)RootView.findViewById(R.id.buttonSub);
buttonMul = (Button)RootView.findViewById(R.id.buttonMul);
buttonDiv = (Button)RootView.findViewById(R.id.buttonDiv);
buttonEqual = (Button)RootView.findViewById(R.id.buttonEqual);
buttonExpense= (Button)RootView.findViewById(R.id.buttonExp);
resultTextView = (TextView)RootView.findViewById(R.id.text_view_result);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("0");
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("2");
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("3");
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("4");
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("5");
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("6");
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("7");
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("8");
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("9");
}
});
buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClearButtonClicked();
}
});
buttonSubstract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
onOperatorButtonClicked("-");
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("+");
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("X");
}
});
buttonDiv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("/");
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqualButtonClicked();
}
});
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(fa2, EditorActivity.class);
startActivity(intent);
((EditorActivity) getActivity()).updateGoldTextView(result);
/*Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra(, result);
final int result2=1;
startActivityForResult(intent, result2);*/
}
});
return RootView;
}
private void onEqualButtonClicked() {
int res = 0;
try {
int number = Integer.valueOf(tmp);
int number2 = Integer.valueOf(resultTextView.getText().toString());
switch (operator) {
case "+":
res = number + number2;
break;
case "/":
res = number / number2;
break;
case "-":
res = number - number2;
break;
case "X":
res = number * number2;
break;
}
result = String.valueOf(res);
resultTextView.setText(result);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void onOperatorButtonClicked(String operator) {
..
}
public void onClearButtonClicked() {
...
}
public void onNumberButtonClicked(String pos) {
..
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}`
EditorActivity.java
package com.example.harshitbahri.expensebook;
import android.app.AlertDialog;
import android.app.LoaderManager;
...
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_EXPENSE_LOADER = 0;
private Uri mCurrentExpenseUri;
private EditText mAmountEditText;
private EditText mDescEditText;
private Spinner mCategorySpinner;
private String mCategory = ExpenseEntry.CATEGORY_GENERAL;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mExpenseHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// Examine the intent that was used to launch this activity,
// in order to figure out if we're creating a new pet or editing an existing one.
Intent intent = getIntent();
mCurrentExpenseUri = intent.getData();
// If the intent DOES NOT contain a pet content URI, then we know that we are
// creating a new pet.
if (mCurrentExpenseUri == null) {
// This is a new pet, so change the app bar to say "Add a Pet"
setTitle("Add Expense");
yet.)
invalidateOptionsMenu();
} else {
// Otherwise this is an existing pet, so change app bar to say "Edit Pet"
setTitle("Edit Expense");
getLoaderManager().initLoader(EXISTING_EXPENSE_LOADER, null, this);
}
mAmountEditText = (EditText) findViewById(R.id.exp_amount);
mDescEditText = (EditText) findViewById(R.id.description);
mCategorySpinner = (Spinner) findViewById(R.id.spinner_category);
.....
}
......
finish();
}
public void updateGoldTextView(String goldAmount) {
mAmountEditText.setText(goldAmount);
}
}
MainActivity.java
package com.example.harshitbahri.expensebook;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
Calculator.OnFragmentInteractionListener ,
Entries.OnFragmentInteractionListener,Info.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final Pageradapter adapter = new Pageradapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setCurrentItem(1, false);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Your fragment is loaded from MainActivity and not EditorActivity, hence the class cast exception. If you want to pre-fill some data in the editor activity, you can pass that in the intent ( the code you commented on your onclick listener) and retrieve in the EditorActivity and set your UI elements.
Edited
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra("result", result);
startActivity(intent);
}});
In your EditorActivity class, in on create
String result=getIntent().getStringExtra("result")
updateGoldTextView(result)

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

I want put edittext from first activity to new secondactivity view text.
What to do when I have an erro like this displayed in android monitor :
com.example.xx.DrawerAddAd.seeAdd(DrawerAddAd.java:129)
com.example.xx.DrawerAddAd.access$100(DrawerAddAd.java:40)
com.example.xx.DrawerAddAd$2.onClick(DrawerAddAd.java:116)
also:
Render problem:
Couldn't resolve resource #id/visible
Tip: Try to refresh the layout.
DrawerAddAd class code:
package com.example.xx.drawer;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import com.example.xx.R;
import com.example.xxx.model.POJO.view.ProductDetails;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import butterknife.BindView;
public class DrawerAddAd extends AppCompatActivity {
public static ArrayList<String> fragments = new ArrayList<>();
private final int REQUEST_CODE = 1;
private ImageButton camera_imageButton;
private Spinner spinner_category;
private Button button_seeAd_product;
private Button button_add_product;
#BindView(R.id.title_Ad_editText)
EditText titleAd_editText;
#BindView(R.id.text_Ad_editText)
EditText textAd_editText;
#BindView(R.id.price_editText)
EditText price_editText;
#BindView(R.id.checkBox_season)
CheckBox checkBox_season;
#BindView(R.id.checkBox_year)
CheckBox checkBox_year;
#BindView(R.id.checkBox_detail)
CheckBox checkBox_detail;
#BindView(R.id.checkBox_wholesale)
CheckBox checkBox_whoLesale;
private int REQUEST_CAMERA = 1, SELECT_FILE = 1;
private Button btnSelect;
private ImageView Image;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_add_ad);
final TextInputLayout title_ad_layout = (TextInputLayout) findViewById(R.id.add_title_ad_layout);
final TextInputLayout text_ad_layout = (TextInputLayout) findViewById(R.id.add_text_ad_layout);
final TextInputEditText title_Ad_editText = (TextInputEditText) findViewById(R.id.title_Ad_editText);
final TextInputEditText text_Ad_editText = (TextInputEditText) findViewById(R.id.text_Ad_editText);
setTextWatcher(title_Ad_editText, title_ad_layout);
setTextWatcher(text_Ad_editText, text_ad_layout);
spinner_category = (Spinner) findViewById(R.id.spinner_category);
button_seeAd_product = (Button) findViewById(R.id.button_seeAd_product);
button_add_product = (Button) findViewById(R.id.button_ad_product);
camera_imageButton = (ImageButton) findViewById(R.id.camera_imageButton);
camera_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
button_seeAd_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean error = false;
if (TextUtils.isEmpty(title_Ad_editText.getText().toString())) {
title_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (TextUtils.isEmpty(text_Ad_editText.getText().toString())) {
text_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (!error) {
seeAdd();
}
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.fragments, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner_category.setAdapter(adapter);
}
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
// ImageView imageView =
// String title = titleAd_editText.getText().toString();
// String text = textAd_editText.getText().toString();
// String price = price_editText.getText().toString();
//
//
// intent.putExtra("titleAdd", title);
// intent.putExtra("textAdd", text);
// intent.putExtra("price", price);
startActivity(intent);
}
private void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch (view.getId()) {
case R.id.checkBox_season:
if (checked) {
} else {
}
break;
case R.id.checkBox_year:
if (checked) {
} else {
}
break;
case R.id.checkBox_detail:
if (checked) {
} else {
}
break;
case R.id.checkBox_wholesale:
if (checked) {
} else {
}
break;
}
}
private void setTextWatcher(final TextInputEditText editText, final TextInputLayout inputLayout) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (inputLayout.isErrorEnabled()) {
inputLayout.setErrorEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
private void selectImage() {
final CharSequence[] items = {"Zrób zdjęcie", "Wybierz z katalogu", "Anuluj"};
AlertDialog.Builder builder = new AlertDialog.Builder(DrawerAddAd.this);
builder.setTitle("Dodaj zdjęcie");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(DrawerAddAd.this);
if (items[item].equals("Zrób zdjęcie")) {
userChosenTask = "Zrób zdjęcie";
if (result)
cameraIntent();
} else if (items[item].equals("Wybierz z katalogu")) {
userChosenTask = "Wybierz z katalogu";
if (result)
galleryIntent();
} else if (items[item].equals("Anuluj")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Wybierz plik"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Image.setImageBitmap(bm);
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Image.setImageBitmap(thumbnail);
}
}
ProductDetails class code:
package com.example.xxx.model.POJO.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import com.example.xxx.R;
public class ProductDetails extends AppCompatActivity {
private TextView title, text, price, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title = (TextView) findViewById(R.id.title_textView);
text = (TextView) findViewById(R.id.text_textView);
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
title.setText(title_textView);
text.setText(text_textView);
// price = (TextView) findViewById(R.id.price_textView);
// date = (TextView) findViewById(R.id.date_textView);
// String titleAdd = bundle.getString("titleAdd");
// String textAdd = bundle.getString("textAdd");
// String price = bundle.getString("price");
// title.setText(titleAdd);
// text.setText(textAdd);
// price.setText(price);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
I don't know what to do ...
Thanks, Slawek.
it means title_Ad_editText is null.
Check your xml file and title_Ad_editText variable.
couple things I could see, redo this:
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
to this:
private void seeAdd() {
Intent intent = new Intent(DrawerAddAd.this, ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
then in your intent, you need to call the extra exactly as set, change this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
to this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("title");
String text_textView = intent.getStringExtra("text");

My ListView acitviity evrytime call previous arraylist when add new data in database

I create an activity thats populate from database and fill to ArrayList.
when add a new data in database and call listview activity thats change ArrayList to last with for example 6 and previous ArrayList with 5 item.
when i finish activity use below code:
Intent intent = new Intent(ListViewClass.this, AddClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
ListViewClass.this.onDestroy();
//NamayeshListYadavar.this.finish();
but when call ListViewClass thasts save previous ArrayList and new ArrayList and evrytime switch between two ArrayList.
When i debug my program show me 2 ArrayList with same name but different id and size.how to i can delete previous ArrayList when finish activity and call AddClass in my project?
Also i use
#Override
public void onDestroy() {
super.onDestroy();
Runtime.getRuntime().gc();
}
but in not work.
please help me friends.
and sorry for bad english.
This is all of my oncreate code
all of my code is :
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.blueprogrammers.utils.SomeUtils;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class NamayeshListYadavar extends HeaderFooter {
//AlarmData[] daro_data;
ArrayList<AlarmData> daro_data = new ArrayList<AlarmData>();
Handler mHandler = new Handler();
String myValue;
List<AlarmData> alarmList;
NamayeshListAdaptor adapter;
ListView list;
public String font1="byekan.ttf";
public String font2="BMitraBd.ttf";
private static final int RUN_EDIT = 1100;
/*** 0 for vibre 1 for melody and 2 for melody and vivre***/
int alarmtype = 2, vibre=0;
Boolean animlockBoolean=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup vg = (ViewGroup) findViewById(R.id.lldata);
ViewGroup.inflate(this, R.layout.yadavar_list, vg);
list = (ListView) findViewById(R.id.yadavar_listview);
createCollection();
adapter = new NamayeshListAdaptor(this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
TextView tv = (TextView) arg1.findViewById(R.id.txtid);
//String text = tv.getText().toString();
myValue = (String) tv.getText();
Intent intent = new Intent(NamayeshListYadavar.this, EditYadavar.class);
intent.putExtra("YADAVAR-ID", myValue);
startActivity(intent);
NamayeshListYadavar.this.finish();
//startActivityForResult(intent, RUN_EDIT);
}
});
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
new textSearh().execute();
}
}, 0, 500);
}
public void clickMe(View v){
switch (v.getId()) {
case R.id.txttarikhetmam:
break;
default:
break;
}
}
class textSearh extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
final SharedPreferences preferences = getSharedPreferences("DaroPref", 0);
final int del = preferences.getInt("delid", 9999);
Boolean checkBoolean =preferences.getBoolean("delbol", false);
if(checkBoolean){
Editor editor = preferences.edit();
editor.putBoolean("delbol", false);
editor.commit();
deleteView(del);
}
}
});
return null;
}
protected void onPostExecute(String file_url) {
}
}
private void createCollection() {
DatabaseHandler db= new DatabaseHandler(this);
alarmList = new ArrayList<AlarmData>();
alarmList = db.getViewAlarm("SELECT AlarmID, idDrug, alarmTime , nameYadavar, done, alarmDate FROM Alarm where done =0");
ArrayList<AlarmData> alarm_dat = new ArrayList<AlarmData>(alarmList);
this.daro_data=alarm_dat;
db.close();
}
public void deleteView(final int del){
createCollection2();
Animation anim = AnimationUtils.loadAnimation(
NamayeshListYadavar.this, android.R.anim.slide_out_right
);
try{
anim.setDuration(500);
list.getChildAt(del).startAnimation(anim );
new Handler().postDelayed(new Runnable() {
public void run() {
createCollection2();
adapter = new NamayeshListAdaptor(NamayeshListYadavar.this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
}
}, anim.getDuration());
}catch(Exception e){
e.printStackTrace();
}
}
public void btnbtnClick(View v)
{
switch (v.getId()) {
case R.id.btnadd:
Intent intent = new Intent(NamayeshListYadavar.this, TanzimSaat.class);
intent.putExtra("CLASS-TYPE", "NamayeshListYadavar");
startActivityForResult(intent, RUN_EDIT);
//startActivityForResult(intent, RUN_EDIT);
break;
case R.id.btnbar:
this.finish();
break;
default:
break;
}
}
#Override
public void onBackPressed() {
this.finish();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RUN_EDIT:
createCollection2();
adapter = new NamayeshListAdaptor(this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
break;
}
}
}
Finally i fixed problem by add below code
public void onBackPressed() {
timer.cancel();
this.finish();
}
Timer is my problem

onActivityResult Is not responding when choosing from a list

Hi Guys I am new with android programming and Java. I am trying to make a travel app. My issue is that how do I pass data from the selected item from the list to the editText filed. This is out I have done so far.. Pls. be kind I am newbee
The activity class that uses the ListActivity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class SelectStationActivity extends ListActivity {
String stations[] = { "Acton Main Line","Ealing","Great Western","Albany Park"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter <String> adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stations);
setListAdapter(adapter);
}
protected void OnListItemClick(ListView l, View v, int position, long id) {
String values = stations[(int) id];
Intent result = new Intent().putExtra("SELECTED_STATION_NAME", values);
setResult(RESULT_OK, result);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.select_station, menu);
return true;
}
The main class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TravelActivity extends Activity {
// The request code for the selectChkInBt
protected static final int SelectChkin_REQUEST_CODE = 1;
// The request code for the selectChkOutBt
protected static final int SelectChkout_REQUEST_CODE = 2;
private String checkinStation;
private String checkoutStation;
private Button checkinButton, checkoutButton, selectChkInButton, selectChkOutButton;
private EditText checkinEditText, checkoutEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_travel);
checkinButton = (Button) findViewById(R.id.btCkIn);
checkoutButton = (Button) findViewById(R.id.BtChkOut);
selectChkInButton = (Button) findViewById(R.id.btselectChkIn);
selectChkOutButton = (Button) findViewById(R.id.btselectChkOut);
checkinEditText = (EditText) findViewById(R.id.EditTxtChkIn);
checkoutEditText = (EditText) findViewById(R.id.EditTxtChkOut);
checkinButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkinEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-in Station", Toast.LENGTH_LONG).show();
} else {
checkinStation = checkinEditText.getText().toString();
// Enable the check-out EditText and Button
checkinEditText.setEnabled(false);
checkinEditText.setTextColor(Color.CYAN);
checkinButton.setEnabled(false);
// Disable the check-in- EdiText AND Button
checkoutEditText.setEnabled(true);
checkoutButton.setEnabled(true);
checkoutEditText.requestFocus();
}
}
});
checkoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkoutEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-Out station", Toast.LENGTH_LONG)
.show();
} else {
checkoutStation = checkoutEditText.getText().toString();
// Clear edit Text
checkoutEditText.setText("");
// Enable the check-in EditText and Button
checkoutEditText.setEnabled(false);
checkoutButton.setEnabled(false);
/*
* Disable the check-out EditText and Button, to allow the
* eternal cycle of checking in and out to commence once again */
checkinEditText.setText("");
checkinEditText.setEnabled(true);
checkinButton.setEnabled(true);
checkinEditText.requestFocus();
Toast.makeText(getApplicationContext(),
"Travel information added!", Toast.LENGTH_SHORT)
.show();
}
}
});
I could implement a inner class for the two select buttons but i have diffculties to do it.Pls. provide some help how I could implement it thanks.
selectChkInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,
SelectStationActivity.class);
startActivityForResult(intent, SelectChkin_REQUEST_CODE);
}
});
selectChkOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,SelectStationActivity.class);
startActivityForResult(intent, SelectChkout_REQUEST_CODE);
}
});
}
The onActivityResult is not responding here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== RESULT_OK){
if (requestCode == 1) {
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, "Recipt");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
public boolean OnMenuItemSelected(int featureId, MenuItem item) {
String Recipt = "Recipt" + item.getItemId() + "\nCheck-in: "
+ checkinStation + "\nCheck-Out: " + checkoutStation;
Toast.makeText(getApplicationContext(), Recipt, Toast.LENGTH_LONG)
.show();
return true;
}
protected void OnSaveInstanceState(Bundle outState) {
outState.putString("lAST_CHECKIN", checkinStation);
outState.putString("lAST_CHECKOUT", checkoutStation);
}
protected void onRestoreInstance(Bundle savedInstanceState) {
checkinStation = savedInstanceState.getString(checkinStation);
checkoutStation = savedInstanceState.getString(checkoutStation);
}
}
You Should use this
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
as
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME").toString());

Categories

Resources