String value is null - android

I have a ListView with each row containing a TextView. On user click, I'm getting the value of the TextView and storing it in a String variable, and the user is navigated to another activity where he / she needs to input some data on said TextView. In order to not lose the information state of the first activity, I had to use startActivityForResult() and later get the information from the second activity with the method onActivityResult().
The problem is this: I need to compare a value with that of the TextView in question, however the String variable which supposedly contains the TextView's value is null.
Before starting up the second activity I toasted the String value and it returned the correct string, however not in the onActivityResult(), where it returns null.
Why is this happening? Isn't the Intent I used suppose to retain all information of the opened activity?
ListView's onItemClick
#Override
public void onItemClick(AdapterView<?> listView, View itemView, int itemPosition, long itemID)
{
clickedError = ((TextView)itemView).getText().toString();
String errorIDQuery = "SELECT _id FROM " + TABLE_ERROR + " WHERE error_description LIKE '" + clickedError + "';";
Cursor getErrorID = db.rawQuery(errorIDQuery, null);
getErrorID.moveToFirst();
errorID = getErrorID.getInt(0);
Intent intent = new Intent(Repair.this, Material.class);
intent.putStringArrayListExtra("materialList", materialList);
startActivityForResult(intent, 1);
Toast.makeText(getApplicationContext(), clickedError, Toast.LENGTH_LONG).show();
}
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK)
{
#SuppressWarnings("unchecked")
HashMap <String, String> materialDetails = (HashMap <String, String>)data.getSerializableExtra("map");
Set<?> set = materialDetails.entrySet();
Iterator<?> i = set.iterator();
ArrayList<String> materialNames = new ArrayList<String>();
ArrayList<String> materialAmounts = new ArrayList<String>();
do
{
#SuppressWarnings("rawtypes")
Map.Entry me = (Map.Entry)i.next();
materialNames.add(me.getKey().toString());
materialAmounts.add(me.getValue().toString());
}
while (i.hasNext());
for(Error e : errorList)
{
// ----- COMPARING THE VALUES -----
// here clickedError is null
if(e.description.equals(clickedError))
{
for(int j = 0; j < materialNames.size(); j++)
{
MaterialClass mc = new MaterialClass();
mc.setName(materialNames.get(j));
mc.setAmount(Integer.parseInt(materialAmounts.get(j)));
e.materialList.add(mc);
}
if (e.materialList.size() != 0)
e.checked = true;
else
e.checked = false;
}
}

My guess: the activity is destroyed and restarted while moving to the second activity. This is easy to confirm with log messages in the activity life cycle methods(onCreate/onRestart/etc).
The following link might be of use to persist data during activity switching: http://developer.android.com/training/basics/activity-lifecycle/recreating.html

Make your String value as static so that it will retain its value. or you can use shared preference to save value and use it later.

This is working if its not ask me
TextView textviewDate=(TextView)findViewById(R.id.yourtextviewid);
clickedError=textviewDate.getText().toString();

Related

next button for listview

My first activity contains a ListView that's getting a list of items from a database.
And in the OnClickListener, there is a new activity that's open getting all information related to the question from the database, I'm putting them in Intent extras and getting them in the next activity:
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
String quest = (String) parent.getAdapter().getItem(i);
int pos = lst.getCheckedItemPosition();
Intent inte = new Intent(view.getContext(),Reponse.class);
cursor = db.rawQuery("SELECT * FROM "+ ModelHelper.TABLE_QUESTION + " WHERE " + ModelHelper.KEY_QUESTION + " = ? ",new String[] {quest});
if (cursor != null)
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String repA = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_WAITEDANSWER));
String cible = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_CIBLE));
String plan = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PLANACT));
int ID = cursor.getColumnIndex(ModelHelper.KEY_ID_QUESTION);
inte.putExtra("question", quest);
inte.putExtra("repo", repA);
inte.putExtra("cible", cible);
inte.putExtra("plan", plan);
// inte.putExtra("id", ID);
// inte.putExtra("pos", pos);
startActivity(inte);
finish();
In the info activity, it's simple and I could get the information from the database, here's the code
Intent intent = getIntent();
String question = intent.getStringExtra("question");
String repo = intent.getStringExtra("repo");
String cible = intent.getStringExtra("cible");
String plan = intent.getStringExtra("plan");
final int[] ID = {0};
ID[0] = intent.getIntExtra("ID", ID[0]);
int pos = 0;
pos = intent.getIntExtra("pos",pos);
txtq.setText(question);
txtr.setText(repo);
txtc.setText(cible);
txtp.setText(plan);
I want to add a button NEXT that makes appear the next item in the list by refreshing the same page without going back to the list and click again.
I tried to get the position too with the intent and tried to set a new OnClickListener in the button to set the position = position +1, but it doesn't work.
Any ideas?
First solution
for that, you have to pass the entire list to next activity so you can directly do next item in the list by refreshing the same page without going back.
Second solution.
You have to separately apply query for next info page click on the next/previous button.
You just need to go through the sql Queries
select * from table where key=primaryKey limit Page_Limit offset Start_From
You need to change limit and offset on select of list limit.

Not able to pass distance variable to another activity using Google Distance Matrix API Android

I have tried work on this for whole day but could find a solution. I am working on a test google map app to learn java.
From this activity when button is clicked, it takes user to another activity and I need some values to be passed to next activity.
I am able to retrieve Start Address as well as destination address in next activity but not the distance.
implements GeoTask.Geo {
private TextView mFromAddress;
private TextView mToAddress;
String str_from,str_to;
int dist;
public void onClickBtn(View v){
str_from = mFromAddress.getText().toString();
str_to = mToAddress.getText().toString();
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=" + str_from + "&destinations=" + str_to + "&mode=driving&language=en-US&avoid=tolls&key=API-Key";
new GeoTask(MapsActivity.this).execute(url);
getResults();
}
// This is called from external class GeoTask.Java
public void setDouble(String result) {
String res[]=result.split(",");
Double min = Double.parseDouble(res[0])/60;
dist = Integer.parseInt(res[1])/1000;
}
public void getResults(){
Intent intent = new Intent(this, ResultsActivity.class);
String fromCity = str_from;
String toCity = str_to;
int kmDistance = dist;
intent.putExtra("from",fromCity);
intent.putExtra("to",toCity);
intent.putExtra("distance",kmDistance);
startActivity(intent);
}
}
I am retrieving these details by
Intent intent = getIntent();
String fromCity = intent.getStringExtra("from");
String toCity = intent.getStringExtra("to");
int kmDistance = intent.getIntExtra("distance", 0);
Reason why you have no distance.
Maybe the AsyncTask is not yet already done while calling the getResults();
Try to remove the getResults(); after calling the new GeoTask(MapsActivity.this).execute(url); and put the getResults(); in onPostExecute(args)

How to remove duplicates from ArrayList of type Object? [duplicate]

This question already has answers here:
How to remove duplicates from a list?
(15 answers)
Closed 8 years ago.
I want to remove duplicates from ArrayList of type Alerts where Alerts is a class.
Class Alerts -
public class Alerts implements Parcelable {
String date = null;
String alertType = null;
String discription = null;
public Alerts() {
}
public Alerts(String date, String alertType, String discription) {
super();
this.date = date;
this.alertType = alertType;
this.discription = discription;
}
}
Here is how I added the elements -
ArrayList<Alerts> alert = new ArrayList<Alerts>();
Alerts obAlerts = new Alerts();
obAlerts = new Alerts();
obAlerts.date = Date1.toString();
obAlerts.alertType = "Alert Type 1";
obAlerts.discription = "Some Text";
alert.add(obAlerts);
obAlerts = new Alerts();
obAlerts.date = Date2.toString();
obAlerts.alertType = "Alert Type 1";
obAlerts.discription = "Some Text";
alert.add(obAlerts);
What I want to remove from them-
I want all alerts which have unique obAlerts.date and obAlerts.alertType. In other words, remove duplicate obAlerts.date and obAlerts.alertType alerts.
I tried this -
Alerts temp1, temp2;
String macTemp1, macTemp2, macDate1, macDate2;
for(int i=0;i<alert.size();i++)
{
temp1 = alert.get(i);
macTemp1=temp1.alertType.trim();
macDate1 = temp1.date.trim();
for(int j=i+1;j<alert.size();j++)
{
temp2 = alert.get(j);
macTemp2=temp2.alertType.trim();
macDate2 = temp2.date.trim();
if (macTemp2.equals(macTemp1) && macDate1.equals(macDate2))
{
alert.remove(temp2);
}
}
}
I also tried-
HashSet<Alerts> hs = new HashSet<Alerts>();
hs.addAll(obAlerts);
obAlerts.clear();
obAlerts.addAll(hs);
You need to specify yourself how the class decides equality by overriding a pair of methods:
public class Alert {
String date;
String alertType;
#Override
public boolean equals(Object o) {
if (this == 0) {
return true;
}
if ((o == null) || (!(o instanceof Alert)))
return false;
}
Alert alert = (Alert) o;
return this.date.equals(alert.date)
&& this.alertType.equals(alert.alertType);
}
#Override
public int hashCode() {
int dateHash;
int typeHash;
if (date == null) {
dateHash = super.hashCode();
} else {
dateHash = this.date.hashCode();
}
if (alertType == null) {
typeHash = super.hashCode();
} else {
typeHash = this.alertType.hashCode();
}
return dateHash + typeHash;
}
}
You can then loop through your ArrayList and add elements if they aren't already there as Collections.contains() makes use of these methods.
public List<Alert> getUniqueList(List<Alert> alertList) {
List<Alert> uniqueAlerts = new ArrayList<Alert>();
for (Alert alert : alertList) {
if (!uniqueAlerts.contains(alert)) {
uniqueAlerts.add(alert);
}
}
return uniqueAlerts;
}
However, after saying all that, you may want to revisit your design to use a Set or one of its family that doesn't allow duplicate elements. Depends on your project. Here's a comparison of Collections types
You could use a Set<>. By nature, Sets do no include duplicates. You just need to make sure that you have a proper hashCode() and equals() methods.
In your Alerts class, override the hashCode and equals methods to be dependent on the values of the fields you want to be primary keys. Afterwards, you can use a HashSet to store already seen instances while iterating over the ArrayList. When you find an instance which is not in the HashSet, add it to the HashSet, else remove it from the ArrayList. To make your life easier, you could switch to a HashSet altogether and be done with duplicates per se.
Beware that for overriding hashCode and equals, some constraints apply.
This thread has some helpful pointers on how to write good hashCode functions. An important lesson is that simply adding together all dependent fields' hashcodes is not sufficient because then swapping values between fields will lead to identical hashCodes which might not be desirable (compare swapping first name and last name). Instead, some sort of shifting-operation is usually done before adding the next atomic hash, eg. multiplying with a prime.
First store your datas in array then split at as one by one string,, till the length of that data execute arry and compare with acyual data by if condition and retun it,,
HashSet<String> hs = new HashSet<String>();
for(int i=0;i<alert.size();i++)
{
hs.add(alert.get(i).date + ","+ alert.get(i).alertType;
}
alert.clear();
String alertAll[] = null;
for (String s : hs) {
alertAll = s.split(",");
obAlerts = new Alerts();
obAlerts.date = alertAll[0];
obAlerts.alertType = alertAll[1];
alert.add(obAlerts);
}

Set a StringArray with sharedpreferences

I'm trying to make a "memory" to save three Dates + Hours in a StringArray.
I 'll explain better with code. In my main activity I call this line:
conf.setDateArray(completeDate, conf.getPosition());
The two parameters are (a String, an int with the position of the array [0 or 1 or 2]).
My problem comes in the Configuration class:
private String[] strDateArray = new String[3];
private int position = 0;
public void setDateArray(String str, int position) {
SharedPreferences.Editor editor = getSettings().edit();
// The problem is this code, I dont know how to write in the array in
// the position
this.strDateArray(position) = str(position);
editor.putString(KEY_DATEARRAY, str);
//
editor.commit();
if (position == 2) {
this.position = 0;
} else {
this.position++;
}
}
Thank you for your help!
EDIT: an example of what I want to do
I want to introduce a date like "20-02-2014 14:14" to the StringArray[0] to let the user get this value when he starts again APP. My intention is to have the last three possible values, when all the array is filled, the position=0 will be overwritten.
private static final String[] KEYS = { "0", "1", "2" };
private static final String POSITION = "LAST_POSITION";
public void setDateArray(String str) { // no need to pass the position in
SharedPreferences prefs = getSettings(); // what's getSettings ?
int pos = prefs.getInt(POSITION, 0); // get the last position - if you kept
// it in a field on app restart you will loose it
final Editor editor = prefs.edit();
editor.putString(KEYS[pos], str);
pos = (pos + 1) % 3; // if pos + 1 == 3 with the %3 you get 0
editor.putInt(POSITION, pos);
editor.commit();
}
Although I am sure there is a simpler way to do this

Problems with putExtra and putStringArrayList

I'm trying to send some data from one activity to another and it's sorta working but not like I want to work.
Problem 1-Things are getting mixed up. On the Next Activity part of the listitem is going to an incorrect textView and part to the correct textview.
Problem 2- I am only able to list 1 item on the new activity but I want to be able to send multiple listitems. I think the problem lies in combining different types of putExtra request to the same place like I do here.
.putExtra("inputPrice",(CharSequence)pick)
.putStringArrayListExtra("list", listItems)
Ant help would be appreciated.
Sending Data to next Activity
final TextView username =(TextView)findViewById(R.id.resultTextView);
String uname = username.getText().toString();
final TextView uplane =(TextView)findViewById(R.id.inputPrice);
String pick = uplane.getText().toString();
final TextView daplane =(TextView)findViewById(R.id.date);
String watch = daplane.getText().toString();
startActivity(new Intent(MenuView1Activity.this,RecordCheckActivity.class)
.putExtra("date",(CharSequence)watch)
.putExtra("Card Number",(CharSequence)uname)
.putExtra("inputPrice",(CharSequence)pick)
.putStringArrayListExtra("list", listItems)
);
finish();
This is the Next Activity
Intent is = getIntent();
if (is.getCharSequenceExtra("Card Number") != null) {
final TextView setmsg = (TextView)findViewById(R.id.saleRccn);
setmsg.setText(is.getCharSequenceExtra("Card Number"));
}
Intent it = getIntent();
if (it.getCharSequenceExtra("date") != null) {
final TextView setmsg = (TextView)findViewById(R.id.saleTime);
setmsg.setText(it.getCharSequenceExtra("date"));
}
Intent id1 = getIntent();
if (id1.getCharSequenceExtra("inputPrice") != null) {
final TextView setmsg = (TextView)findViewById(R.id.saleName);
setmsg.setText(id1.getCharSequenceExtra("inputPrice"));
}
ArrayList<String> al= new ArrayList<String>();
al = getIntent().getExtras().getStringArrayList("list");
saleNotes= (TextView) findViewById(R.id.saleNotes);
saleNotes.setText(al.get(0));
Alright, a few things:
First of all you do not need to cast your strings as CharSequence.
Second thing,
Define intent, add your extras and only then call startActivity as below:
Intent intent = new Intent(MenuView1Activity.this,RecordCheckActivity.class);
intent.putExtra("date", watch);
startActivity(intent);
Third, when retrieving the intent create a bundle first as below:
Bundle extras = getIntent().getExtras();
String date = extras.getString("date");
EDIT:
Here is how you convert your entire array list to one single string and add it to your textview.
String listString = "";
for (String s : al)
{
listString += s + "\t"; // use " " for space, "\n" for new line instead of "\t"
}
System.out.println(listString);
saleNotes.setText(listString);
Hope this helps!
Try this, Don't use CharSequence just put string value
startActivity(new Intent(MenuView1Activity.this,RecordCheckActivity.class)
.putExtra("date",watch)
.putExtra("Card Number",uname)
.putExtra("inputPrice",pick)
.putStringArrayListExtra("list", listItems)
);
And get like this
Intent is = getIntent();
if (is.getCharSequenceExtra("Card Number") != null) {
final TextView setmsg = (TextView)findViewById(R.id.saleRccn);
setmsg.setText(is.getStringExtra("Card Number"));
}

Categories

Resources