setTextColor() - Logic Error - java

Hello I'm Having a problem with my simple Android Application, it can't change the Text Colors in the other Activity which is displayActivity.java Here's my Code sample.
The problem is if the texts are both equal it will change into color greensuccess
but it did change into rederror
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String xy = "ict402.germio.intent";
public static final String xz = "ict402.germio.intent";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void send(View view){
EditText a = findViewById(R.id.a);
EditText b = findViewById(R.id.b);
String strx =(a.getText().toString());
String stry =(b.getText().toString());
if (strx.compareToIgnoreCase(stry) == 0)
{
// this line WILL print
Intent i = new Intent(this, displayActivity.class);
String t = ("Case Ignored \n VALUES ARE THE SAME CONGRATS!").toString();
i.putExtra(xy,t);
startActivity(i);
} else {
Intent i = new Intent(this, displayActivity.class);
String y = ("Case Ignored \n VALUES ARE NOT THE SAME SORRY!").toString();
i.putExtra(xz,y);
startActivity(i);
}
}
}
displayActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Intent i = getIntent();
String message = i.getStringExtra(MainActivity.xy);
TextView t = findViewById(R.id.x);
t.setTextColor(getResources().getColor(R.color.success));
t.setText(message);
Intent o = getIntent();
String msg = o.getStringExtra(MainActivity.xz);
TextView q = findViewById(R.id.x);
q.setTextColor(getResources().getColor(R.color.error));
q.setText(msg);
}
}

There are so many things wrong. Here's a replacement:
public void send(View view) {
String editTextAContents = findViewById(R.id.a).getText().toString();
String editTextBContents = findViewById(R.id.b).getText().toString();
Intent intent = new Intent(this, DisplayActivity.class);
if (editTextAContents.equalsIgnoreCase(editTextBContents)) {
intent.putExtra("message", "Case Ignored \n VALUES ARE THE SAME CONGRATS");
intent.putExtra("error", false);
} else {
intent.putExtra("ict402.germio.intent", "Case Igored \n VALUES ARE NOT THE SAME SORRY!");
intent.putExtra("error", true);
}
startActivity(intent);
}
In DisplayActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Intent intent = getIntent();
String message = intent.getStringExtra("message");
boolean hasError = intent.getBooleanExtra("error", false);
TextView textView = findViewById(R.id.x);
textView.setText(message);
if (hasError) {
textView.setTextColor(ContextCompat.getColor(this, R.color.error));
} else {
textView.setTextColor(ContextCompat.getColor(this, R.color.success));
}
}
When you populate an Intent's extras, they must have a different name.
When you declare variables, be more verbose instead of naming them x, y, z, a, b, c so they are more readable.

You're not using any conditional logic to determine what color to use.
You need to do something like this:
TextView t = findViewById(R.id.x);
String successMessage = getIntent().getStringExtra(MainActivity.xy);
String errorMessage = getIntent().getStringExtra(MainActivity.xz);
if(successMessage != null){
t.setTextColor(getResources().getColor(R.color.success));
t.setText(successMessage);
}else if(errorMessage != null){
t.setTextColor(getResources().getColor(R.color.error));
t.setText(errorMessage);
}
A better way of doing it is by sending a boolean through the intent to help you determine what color to set. Here is an example:
Intent i = new Intent(this, displayActivity.class);
if (strx.equalsIgnoreCase(stry)){
i.putExtra("message","Case Ignored \n VALUES ARE THE SAME CONGRATS!");
i.putExtra("success", true);
} else {
i.putExtra("message","Case Ignored \n VALUES ARE NOT THE SAME SORRY!");
i.putExtra("success", false);
}
startActivity(i);
And in the other activity, do this:
TextView t = findViewById(R.id.x);
Intent i = getIntent();
String message = getIntent().getStringExtra("message");
boolean success = getIntent().getBooleanExtra("success");
t.setText(message);
t.setTextColor(getResources().getColor(success ? R.color.success : R.color.error));

Related

Intents keep coming back null

So Im making a simple organization app and once I getIntent() and set variables to whatever i used .putExtra() on and it just wont transmit the data between views, could it be that I copied the code from a different app I've made and adapted it or what? because when I do getStringExtra
it comes up as null (which i've tested by setting some buttons text to the getStringExtra and it shows up blank)and doesnt have a value. Even though everything should be correct, can someone just look this over please and tell me whats up?
code from main activity
#Override
public void onResume() {
super.onResume();
if(test==1){
Intent itemCreate = getIntent();
itemName = itemCreate.getStringExtra(CreateItem.NAME_TEXT);
itemLocation = itemCreate.getStringExtra(CreateItem.LOCATION_TEXT);
itemDesc = itemCreate.getStringExtra(CreateItem.DESC_TEXT);
items.add(new Item(itemName, itemLocation, itemDesc));
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
// itemNames.add(items.get(items.size()-1).getName());
addItem.setText(itemName);
toast.show();
if(items!=null) {
lv.setAdapter(adapter);
} //toast.show();
}
}
code from sending activity
public void openMainActivity() {
editName = (EditText) findViewById(R.id.itemNameText);
editLoc = (EditText) findViewById(R.id.itemLocationText);
editDesc = (EditText) findViewById(R.id.itemPriceText);
String name = editName.getText().toString();
String location = editLoc.getText().toString();
String desc = editDesc.getText().toString();
Intent itemCreate = new Intent(this, MainActivity.class);
itemCreate.putExtra(NAME_TEXT, name);
itemCreate.putExtra(LOCATION_TEXT, location);
itemCreate.putExtra(DESC_TEXT, desc);
itemCreate.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(itemCreate);
}
In the receiving activity have you tried as follows:
#Override
public void onResume() {
super.onResume();
if(test==1){
Intent itemCreate = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
itemName = itemCreate.getString(CreateItem.NAME_TEXT);
itemLocation = itemCreate.getString(CreateItem.LOCATION_TEXT);
itemDesc = itemCreate.getString(CreateItem.DESC_TEXT);
items.add(new Item(itemName, itemLocation, itemDesc));
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
// itemNames.add(items.get(items.size()-1).getName());
addItem.setText(itemName);
toast.show();
}
if(items!=null) {
lv.setAdapter(adapter);
} //toast.show();
}
}
Try this:
For checking if your string in being received or not, you can use Logcat:
////add this on receiving activity, in Logcat search using the key "aaaaaa"
////if you received it, it will show you the received text in logcat .
String s = getIntent().getStringExtra("NAME_TEXT");
Log.i("aaaaaaa",s);
/////put the key under double quotation/////
public void openMainActivity() {
editName = (EditText) findViewById(R.id.itemNameText);
editLoc = (EditText) findViewById(R.id.itemLocationText);
editDesc = (EditText) findViewById(R.id.itemPriceText);
String name = editName.getText().toString();
String location = editLoc.getText().toString();
String desc = editDesc.getText().toString();
Intent itemCreate = new Intent(this, MainActivity.class);
itemCreate.putExtra("NAME_TEXT", name);
itemCreate.putExtra("LOCATION_TEXT", location);
itemCreate.putExtra("DESC_TEXT", desc);
itemCreate.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(itemCreate);
}
in receiving activity: make sure that getStringExtra does not get null value, you can use the getIntent() method directly.
#Override
public void onResume() {
super.onResume();
if(test==1){
itemName = getIntent().getStringExtra("NAME_TEXT");
itemLocation = getIntent().getStringExtra("LOCATION_TEXT");
itemDesc = getIntent().getStringExtra("DESC_TEXT");
items.add(new Item(itemName, itemLocation, itemDesc));
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
// itemNames.add(items.get(items.size()-1).getName());
addItem.setText(itemName);
toast.show();
if(items!=null) {
lv.setAdapter(adapter);
} //toast.show();
}
}

Send data with PutExtra when clicking back button

I have the following problem.
Activity 1: Where do I send a user ID by PutExtra.
Activity 2: Get the data with GetExtra.
At some point in Activity 2 I send to Activity 3, sending is done again with PutExtra.
I want to go back to activity 2, sending the data as PutExtra. But in activity 2 you already have a GetExtra that expects the data from activity 1, so it is giving an error. How can I send this data from Activity 3 to Activity 2 and not conflict with Activity 2 because I already expect data with GetExtra from Activity 1.
Note: The data sent is always the same. It is always the user ID that is sent as PutExtra and also received as GetExtra.
EDIT:
Code sending or given from Activity 2 to Activity 3
public class PerfilEmpTab2 extends Fragment {
private RecyclerView mCardServicoList;
private String mId_Empresa = null;
private DatabaseReference mDatabaseServicos;
private boolean mProcessAddServico = false;
public PerfilEmpTab2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_perfil_emp_tab2, container, false);
/* Recebe id de outra tela*/
mId_Empresa = getActivity().getIntent().getExtras().getString("id_empresa");
mDatabaseServicos = FirebaseDatabase.getInstance().getReference().child("Produtos_Empresas").child(mId_Empresa);
/*Recuperar REcyclerView*/
mCardServicoList = (RecyclerView) view.findViewById(R.id.cardListaServicos);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
//mCardCategList.setHasFixedSize(true);
mCardServicoList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
/*Fim Recycler View*/
loadServicos();
return view;
}
private void loadServicos() {
FirebaseRecyclerAdapter<CardServico_row, CardServicosViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<CardServico_row, CardServicosViewHolder>(
CardServico_row.class,
R.layout.card_servicos_row,
CardServicosViewHolder.class,
mDatabaseServicos
) {
#Override
protected void populateViewHolder(final CardServicosViewHolder viewHolder, final CardServico_row model, int position) {
final String servico_key = getRef(position).getKey();
final String nome_produto = model.getNome_produto();
final String duracao = model.getDuracao();
final String valor = model.getValor();
final String valorOld = model.getValorOld();
viewHolder.setNome_produto(model.getNome_produto());
viewHolder.setDuracao(model.getDuracao());
viewHolder.setValor(model.getValor());
viewHolder.setValorOld(model.getValorOld());
/*Clique na view*/
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentServicoDetalhes = new Intent(getActivity(), ServicoDetalhes.class);
intentServicoDetalhes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentServicoDetalhes.putExtra("id_empresa", mId_Empresa);
startActivity(intentServicoDetalhes);
}
});
viewHolder.mAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(Categorias.this, nome + post_key, Toast.LENGTH_LONG).show();
CharSequence opcoes[] = new CharSequence[] {"Editar Serviço", "Ver Detalhes"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//builder.setTitle("Opçoes");
//builder.setCancelable(false);
builder.setItems(opcoes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
switch (which) {
case 0:
Toast.makeText(getActivity().getApplication(), "Dados" + "-" + servico_key + "-" + nome_produto + "-" + duracao + "-" + valor + "-" + valorOld, Toast.LENGTH_LONG).show();
/*Intent criarSubC = new Intent(Categorias.this, CadastroSubCategorias.class);
criarSubC.putExtra("id_categ", post_key);
startActivity(criarSubC);*/
mProcessAddServico = false;
break;
case 1:
Toast.makeText(getActivity().getApplication(), "Dados" + "-" + servico_key + "-" + nome_produto + "-" + duracao + "-" + valor + "-" + valorOld, Toast.LENGTH_LONG).show();
mProcessAddServico = false;
break;
}
}
});
builder.show();
}
});
}
};
mCardServicoList.setAdapter(firebaseRecyclerAdapter);
}
public static class CardServicosViewHolder extends RecyclerView.ViewHolder{
View mView;
ImageButton mAddBtn;
public CardServicosViewHolder (View itemView){
super(itemView);
mView = itemView;
mAddBtn = (ImageButton) mView.findViewById(R.id.addServico_tab2);
}
public void setNome_produto(String nome_produto){
TextView card_nomeProduto = (TextView) mView.findViewById(R.id.tvNomeProduto);
card_nomeProduto.setText(nome_produto);
}
public void setDuracao(String duracao){
TextView card_duracao = (TextView) mView.findViewById(R.id.tvDuracao);
card_duracao.setText(duracao);
}
public void setValor(String valor){
TextView card_valor = (TextView) mView.findViewById(R.id.tvValor);
card_valor.setText(valor);
}
public void setValorOld(final String valorOld){
if ( valorOld != null ){
TextView card_valorOld = (TextView) mView.findViewById(R.id.tvValorOld);
card_valorOld.setText(valorOld);
card_valorOld.setPaintFlags(card_valorOld.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // Risca o texto
//card_valorOld.setPaintFlags(card_valorOld.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); // Remove o Risca o texto
} else {
TextView card_valorOld = (TextView) mView.findViewById(R.id.tvValorOld);
card_valorOld.setText(valorOld);
card_valorOld.setVisibility(View.GONE);
}
}
}
}
In Activity 3 I get:
mId_Empresa = getIntent().getExtras().getString("id_empresa");
When you start activity 3 call startActivityForResult(intent, code) instead of startActivity(intint). Then in Activity 3 override finish() and call setResult(Activity.RESULT_OK, data) where data is an object that you have created new Intent() and called putExtra data.putExtra(key, value) on as you want. Then in Activity 2 override onActivityResult(int requestCode, int resultCode, Intent data) to handle it. requestCode is the code you started the activity with. Be aware that onActivityResult occurs before onResume so attempting to update the UI from onActivityResult might not work as expected eg notifying an adapter.
Refer to this doc for more info
https://developer.android.com/training/basics/intents/result.html
EDIT: added code example
Starting activity 3 from activity 2:
static final int SERVICO_DETALHES_REQUEST = 1; // The request code
#Override
public void onClick(View view) {
{
Intent intentServicoDetalhes = new Intent(getActivity(), ServicoDetalhes.class);
intentServicoDetalhes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentServicoDetalhes.putExtra("id_empresa", mId_Empresa);
startActivityForResult(intentServicoDetalhes, SERVICO_DETALHES_REQUEST );
}
Setting the result from activity 3:
#Override
public void finish()
{
Intent data = new Intent();
data.putExtra("id_empresa", "new_id");
setResult(Activity.RESULT_OK, data);
super.finish();
}
Handling the result from activity 2:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SERVICO_DETALHES_REQUEST && resultCode == RESULT_OK)
String newId = data.getStringExtra("id_empresa");
}

Calling Class to another activity

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.

Passing values to activities and reciveving them in url

I am trying to receive an integer in url.
This how i pass value from one activity to another:
private void displayCategoriesInformation(CategoriesModel categoriesModel) {
//get references to your views
TextView tvCategoryId = (TextView) findViewById(R.id.tvCategoryId);
final int categoryId = categoriesModel.getId();
//set values from your categoriesModel java object to textView
tvCategoryId.setText("Id : " + categoriesModel.getId());
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Categories.this, SubCategories.class);
intent.putExtra("parameter_name", categoryId);
startActivity(intent);
}
});
}
in SubCategory.class i receive it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_subcategory);
Intent intent = getIntent();
int recivedId = intent.getIntExtra("parameter_name", 2);
TextView tvRecivedId = (TextView) findViewById(R.id.tvRecivedId);
tvRecivedId.setText("recivedId" + recivedId);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
spinnerFood = (Spinner) findViewById(R.id.spinFood);
okButton = (Button) findViewById(R.id.bOk);
// spinner item select listener
spinnerFood.setOnItemSelectedListener(this);
new JSONTask().execute("http://146.185.178.83/resttest/subCategories");
}
now the value is stored in the variable recivedId which is 1 or 2 or 3 or 4
what i want to do is execute this JSONTask url like this
new JSONTask().execute("http://146.185.178.83/resttest/categories/recivedId/subCategories");
so the end url would look like this http://146.185.178.83/resttest/categories/1/subcategories/
how can i achieve this
String url = "http://146.185.178.83/resttest/categories/" + recivedId +"/subcategories/";
new JSONTask().execute(url);

Save and load Contacts when swapping Activities

Hey guys maybe someone of you can help me:
What im doing: I have a button in my ContactView that lets me select a phonecontact and inserts name and phonenumber into textviews.
The Problem I have is that when i swap between MainActivity and ContactActivity the Contact is deleted and i need to select again a contact
Here is my ContactView code
public class ContactView extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85;
private TextView textView1;
private TextView textView2;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
textView1 = (TextView) findViewById(R.id.TxtName);
textView2 = (TextView) findViewById(R.id.TxtNumber);
editText = (EditText) findViewById(R.id.editText);
}
public void onClick(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("ContactView", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
*
* #param data
*/
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
// Set the value to the textviews
textView1.setText(name);
textView2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
}
This is the code within my MainAcitivty for the ContactButton that lets me go to ContactView:
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_contactView)
{
Intent ContactIntent = new Intent(this, ContactView.class);
startActivity(ContactIntent);
}
return true;
}
is there a way to check if my intent data is empty? or somehow save the strings as long they are not null?
WITH SHAREDPREFERENCE:
public class ContactView extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85;
private TextView textView1;
private TextView textView2;
private EditText editText;
public SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
textView1 = (TextView) findViewById(R.id.TxtName);
textView2 = (TextView) findViewById(R.id.TxtNumber);
editText = (EditText) findViewById(R.id.editText);
SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
String name = settings.getString("contactName", "");//the second parameter set a default data if “contactName” is empty
if (!name.isEmpty()){
textView1.setText(name);
}
String phoneNo = settings.getString("contactPhone", "");//the second parameter set a default data if “contactName” is empty
if (!phoneNo.isEmpty()){
textView2.setText(phoneNo);
}
}
public void onClick(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("ContactView", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
*
* #param data
*/
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
// Set the value to the textviews
textView1.setText(name);
textView2.setText(phoneNo);
SharedPreferences.Editor editor = settings.edit();
editor.putString("contactName",name );
editor.putString("contactPhone", phoneNo);
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
If you want to save the state of an activity use SharedPreferences
SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(“contactName”,name );
editor.putString(“contactPhone”,phoneNo);
editor.commit();
now in your onCreate of ContactView check if that variables contains data
SharedPreferences settings = getSharedPreferences(“SelectedContact”, MODE_PRIVATE);
String name = settings.getString(“contactName”, “”);//the second parameter set a default data if “contactName” is empty
if (!name.isEmpty()){
yourEditText.setText(name);
}
I hope this helps you.
Tell me if this works!

Categories