how to make getter setter method for string array - android

public class GlobalVariable extends Application {
private static String[] array;
public static void setarray(String[] array) {
GlobalVariable.array = Arrays.copyOf(array, array.length);
}
public static String[] getArray() {
return Arrays.copyOf(array, array.length);
}
}
i have use it like this
String []array = new String[list.size()];
for(int i1 = 0; i1 < list.size(); i1++)
{
array[i1] = list.get(i1);
System.out.println("this is from array"+array[i1]);// this statment running proper.. displays in my logcate
}
GlobalVariable.setarray(array);
}
now i want this value in another activity that extends Frgment
i have use it like:
String[] array1 = new String[1000];
array1 = GlobalVariable.getArray();
for(int i=0;i<array1.length;i++)
{
System.out.println(array1[i]);
}
But it crashes my application by saying null pointer exception how to use it?

Related

How to add data in array on button click?

int size = mcq.size();
String arr[] = null;
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr[i] = tv1.getText().toString();
// Log.e("Array",arr[i]);
} else if (op2.isPressed()) {
arr[i] = tv2.getText().toString();
//Log.e("Array",arr[i]);
} else if (op3.isPressed()) {
arr[i] = tv3.getText().toString();
// Log.e("Array",arr[i]);
} else if (op4.isPressed()) {
arr[i] = tv4.getText().toString();
//Log.e("Array",arr[i]);
}
I am trying to store the data in an array when the button is pressed,but it always shows null.And when the for loop is over I want to display my array.
here , Arrays in Java have a size so u cannot do like this. Instead of this
use list,
ArrayList<String> arr = new ArrayList<String>();
Inorder to do using String array :
String[] arr = new String[SIZEDEFNE HERE];
For ur answer :
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr.add(tv1.getText().toString());
} else if (op2.isPressed()) {
arr.add(tv2.getText().toString());
} else if (op3.isPressed()) {
arr.add(tv3.getText().toString());
} else if (op4.isPressed()) {
arr.add(tv4.getText().toString());
}
Retrive value using
String s = arr.get(0);
This is because your string array is null. Declare it with the size as
String[] arr = new String[size];
Try Array List. use the following code in your main java
final ArrayList<String> list = new ArrayList<String>();
Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(editText.getText().toString());
}
});
To avoid duplication in arraylist .You can use arraylist for faster then String array
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);

array list item get repeated every time when i run my app

Hi i face a problem my arraylist view item get duplicated every time when i run app.
I store all the item of arraylistview in my string.xml file
public class Button_mak extends Activity implements OnClickListener{
final Context context = this;
public static ArrayList<Advertisement> ads = new ArrayList<Advertisement>();
private void populateAdsFromMetadata() {
String [] titles = getResources().getStringArray(R.array.title);
String [] detailedMessages = getResources().getStringArray(R.array.detailed_message);
String [] ownerName = getResources().getStringArray(R.array.owner_name);
String [] ownerEmail = getResources().getStringArray(R.array.owner_email);
String [] price = getResources().getStringArray(R.array.price);
String [] image = getResources().getStringArray(R.array.images);
String [] id = getResources().getStringArray(R.array.id);
for(int i = 0; i < titles.length; i++){
Advertisement ad1 = new Advertisement(titles[i],
detailedMessages[i], ownerName[i],
ownerEmail[i], image[i], Integer.parseInt(price[i]), Integer.parseInt(id[i]));
ads.add(ad1);
}
}
You can keep public static ArrayList<Advertisement> adsto avoid recreating the list everytime..Instead you can clear the list before adding new set of elements.Something like below:
ads.clear();
for(int i = 0; i < titles.length; i++){
Advertisement ad1 = new Advertisement(titles[i],
detailedMessages[i], ownerName[i],
ownerEmail[i], image[i], Integer.parseInt(price[i]), Integer.parseInt(id[i]));
ads.add(ad1);
}

how to pass 2 dimensional array to as a intent in the android

I want to pass the following array to my receiver class in the same format and fetch it in same format i.e the array should maintain its structure.
curDts= new String[][] {{"1","2","3"}, {}, {"4","5","6"}};
Following is what I have tried so far,
Intent intent = new Intent(this, AlarmReceiver.class);
for(int i = 0; i<curDts.length ; i++){
for(int j = 0; j<curDts[i].length; j++){
intent.putExtra("date"+i,"'"+curDts[i][j]+"',");
Log.v("sending","'"+curDts[i][j]+"',");
}
}
for(int i=0; i<12; i++){
Log.v("",""+arg1.getExtras().getString("date"+i));
}
String[] are serializable objects as well as String[][] that means you can simply use the ready method in the intent intent.putExtra(key,serializableObject) , and on your receiver side you could say intent.getSerializableExtra(KEY);
if that what you was looking for.
Edited
To pass your data do something like :
Object[] objArr = new Object[]{ new String[]{"2"} ,new String[]{"5"}};
intent.putExtra("dates", objArr);
and to retreive them :
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Object[] obj = (Object[]) intent.getSerializableExtra("dates");
if(obj != null){
for (int i = 0; i < obj.length; i++) {
String[] object = (String[])obj[i];
Log.d(getClass().getSimpleName(), "OBJ : " + object[0]);
}
}
}
};
You Can simply do like this:
in the first class:
String[][] bidderList;
Intent intent = new Intent(class1.this, class2.class);
intent.putExtra("bidderList",bidderList);
startActivity(intent);
finish();
Then in the second class where you want to receive the 2d array do like this:
String[][] bidderList;
bidderList =(String[][]) getIntent().getSerializableExtra("bidderList");
And that is all :>, you will need to use for loop to access the String[][] array elements
One way to do this is to encode each String array within the larger array of arrays into a String, and pass a String array through the Intent. This String array can be decoded by the Activity receiving the Intent.
I wrote a class that can encode/decode a String array, which can be found here: https://gist.github.com/liangricha/10759438.
Alternatively, you can look into Serialization.
You can pass integers, and you can pass String[], so:
int i = 0;
intent.putExtra("size", curDts.length);
for (String[] value : curDts) {
intent.putExtra("item"+ i++, value);
}
To retrieve it:
int size = intent.getIntExtra("size", 0);
String[][] curDts = new String[][size];
for (int i = 0; i < size; i++) {
curDts[i] = intent.getStringArrayExtras('item" + i);
}
// try this way,hope this will help you...
Note : try to use ArrayList<ArrayList<String>> insted of two dimensional which can be easy Serializable.
**FirstActivty**
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
ArrayList<String> first = new ArrayList<String>();
first.add("1");
first.add("2");
first.add("3");
ArrayList<String> second = new ArrayList<String>();
second.add("4");
second.add("5");
second.add("6");
ArrayList<String> third = new ArrayList<String>();
third.add("7");
third.add("8");
third.add("9");
list.add(first);
list.add(second);
list.add(third);
Intent intent =new Intent(this,MyActivity2.class);
intent.putExtra("SerializableList",list);
startActivity(intent);
}
}
**SecondActivity**
public class MyActivity2 extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
ArrayList<ArrayList<String>> list = (ArrayList<ArrayList<String>>) getIntent().getSerializableExtra("SerializableList");
for (int i=0;i<list.size();i++){
ArrayList<String> row = list.get(i);
for (int j=0;j<row.size();j++){
System.out.println("ParentIndex >> ChildIndex >> Value "+i+" >> "+j+" >> "+row.get(j));
}
}
}
}

Retrieving String[] from JSONObject from sharedPreferences

I was following Micers Answer store and retrieve a class object in shared preference
But how do I retrieve back STring[] from JSOnObject
my class is :
public class AppearExamState implements Serializable{
private static final long serialVersionUID = 1L;
Boolean flag = false;
int questionId;
int subjectId;
String[] storedAnswers;
public AppearExamState(int q, int subjId, String[] ans, boolean flg){
questionId = q;
subjectId = subjId;
storedAnswers = ans;
flag = flg;
} .......
.........getters and setters.....
.......
//-----------------------------------------------------------------
// Here I convert myObject to JsonObject
//-----------------------------------------------------------------
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Qid", this.questionId);
obj.put("Stored_Ans", this.storedAnswers);// is this RIGHT??
obj.put("subj_id", this.subjectId);
obj.put("Flag", this.flag);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
Now when I store in sharepref I followed micers answer and did this:
//--------------------------------------------------------------------------------------
public void sendSharedPreference(ArrayList<AppearExamState> arrayl){
SharedPreferences mPrefs = this.getSharedPreferences("aimmds_state", 0);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Set<String> set= new HashSet<String>();
for (int i = 0; i < arrayl.size(); i++) {
set.add(arrayl.get(i).getJSONObject().toString());
}
prefsEditor.putStringSet("aimmds_state", set);
prefsEditor.commit();
}
//--------------------------------------------------------------------------------------
and I am stuck here with no clue how to do this
public ArrayList<AppearExamState> loadFromStorage(Context c) {
SharedPreferences mPrefs = c.getSharedPreferences("aimmds_state", 0);
ArrayList<AppearExamState> items = new ArrayList<AppearExamState>();
Set<String> set = mPrefs.getStringSet("aimmds_state", null);
for (String s : set) {
try {
JSONObject jsonObject = new JSONObject(s);
int Quesid = jsonObject.getInt("Qid");
int SubjId = jsonObject.getInt("subj_id");
Boolean flag = jsonObject.getBoolean("Flag");
String[] StoAnswer = ????? ;
AppearExamState myclass = new AppearExamState(Quesid, SubjId, StoAnswer, flag );
items.add(myclass);
} catch (JSONException e) {
e.printStackTrace();
}
}
return items;
}
You cannot put an array to JSON, but you can put a Collection, which is represented by a JSONArray (http://www.json.org/javadoc/org/json/JSONObject.html#put%28java.lang.String,%20java.util.Collection%29). So the correct way to put your array to JSONObject is:
obj.put("Stored_Ans", new JSONArray(this.storedAnswers));
and to get:
JSONArray jsonArray = jsonObject.getJSONArray("Stored_Ans");
String[] StoAnswer = new String[jsonArray.length()];
for(i = 0; i < jsonArray.length(); i++){
StoAnswer[i] = jsonArray.getString(i);
}

HashSet to ArrayList not Displaying in Listview

So this project is driving me insane. Thank you to Ahmed Aeon Axan for the last answer. I have never worked with HashTables before but from the all the code I've looked at this should be working. Please tell me why this is not displaying in my listview.
Created in the model.java below
public class Model implements Serializable {
public static final int END_MORNING = 11; // 11:00AM, inclusive
public static final int END_AFTERNOON = 16; // 4:00PM, inclusive
private GregorianCalendar startDate;
private ArrayList<GregorianCalendar> datesSmoked = new ArrayList<GregorianCalendar>();
private ArrayList<String> locationsSmoked = new ArrayList<String>();
private ArrayList<String> locations = new ArrayList<String>();
private ArrayList<String> allIncidents = new ArrayList<String>();
private Set<String> newLocArr = new HashSet<String>(locations);
private SimpleDateFormat sdf = new SimpleDateFormat("E, MMM dd");
private ArrayList<String> times = new ArrayList<String>();
public String [] defaultLocations = {"Home", "Work", "Commuting", "School", "Bar", "Restaurant", "Social Gathering", "Other"};
public String [] eachSmoked;
public Model(GregorianCalendar date){
startDate = date;
for (String s : this.defaultLocations) {
locations.add(s);
}
}
public Model(){
this(new GregorianCalendar()); // now
}
public ArrayList<String> getDates() {
for (int i = 0; i < datesSmoked.size(); i++) {
String s = (sdf.format(i));
times.add(s);
}
return times;
}
public List<String> getPlacesSmoked() {
for (String key : locations) {
newLocArr.add(key+ ": " + Collections.frequency(locationsSmoked, key));
}
return new ArrayList<String>(newLocArr);
}
public ArrayList<String> getAllIncidentsArray() {
for (int i = 0; i < datesSmoked.size(); i++) {
allIncidents.add(getDates().get(i) + ", " + locationsSmoked.get(i));
}
return allIncidents;
}
public ArrayList<String> getlocationsArray() {
return this.locations;
}
public ArrayList<String> getLocationsSmokedArray() {
return this.locationsSmoked;
}
public ArrayList<GregorianCalendar> getDatesSmokedArray() {
return this.datesSmoked;
}
Ends the relevant code for model.java
called into the list view in the Locations Activity below where it is not displaying
public class LocationActivity extends Activity {
public static final String SMOKIN_DATA_FILE = "smokin.dat";
public static Model model = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
restoreModel();
ListView listView = (ListView) findViewById(R.id.location_listview_Id);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, model.getPlacesSmoked());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
Essentially Im trying to get the ArrayList locationsSmoked which Displays
Home
Home
Home
Home
School
School
School
School
to display
Home: 4
School: 4
Your locTest list is empty, since it is initialized at the Model creation with empty HashSet test1 which is initialized with empty locations list.
The List(Collection<?>) constructor is copying the values, not the pointer to the collection, as far as I remember
fast solution (not sure if it do the trick actually):
public Model(GregorianCalendar date){
startDate = date;
for (String s : this.defaultLocations) {
locations.add(s);
}
// calling setPlacesSmoked to process data
setPlacesSmoked();
}
public void setPlacesSmoked() {
// assuming that locations list holds the data needed to process
for (String key : locations) {
test1.add(key+ ": " + Collections.frequency(locations, key));
}
}
public List<String> getPlacesSmoked() {
//return locTest;
return new ArrayList<String>(test1);
}
The expected output:
Home: 1
Work: 1
Commuting: 1
School: 1
Bar: 1
Restaurant: 1
Social Gathering: 1
Other: 1
But that depends on the locations contents

Categories

Resources