How to store dynamically generating Textviews values in Shared preferences Android - android

I am querying the android Contact class and able to fetch contact name plus number and able to add multiple textviews in linear layout with number and name of the contact and able to save single textview number value in shared preferences and retrive it, how can I save dynamically adding textviews array of values (phone numbers (strings) in shared preferences. If any one provide sample code it will help me a lot, as I am doing this for the first time, by the way i searched a lot about this topic but no luck.
Here is my code:
public class Cont extends Fragment {
protected static final int PICK_CONTACT = 0;
Button showConts;
TextView[] resultTextView;
ViewGroup addItems;
final int N = 1;
String name;
String cNumber;
String[] array;
String nameContact;
String number;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contViews = inflater.inflate(R.layout.cont, container, false);
addItems = (LinearLayout) contViews.findViewById(R.id.adds);
showConts = (Button) contViews.findViewById(R.id.opens);
resultTextView = new TextView[N]; //create an empty array;
// create a new textview
for (int i = 0; i < N; i++) {
final TextView rowTextView = new TextView(getActivity());
resultTextView = new TextView[N]; // create an empty array;
addItems.addView(rowTextView);
resultTextView[i] = rowTextView;
if(resultTextView[i] != null ){
resultTextView[i].setText(nameContact+ " "+ cNumber);
}
}
showConts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
return contViews;
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
switch(reqCode)
{
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getActivity().managedQuery(contactData, null, null, null, null);
if (c.moveToFirst())
{
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
{
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
phones.moveToFirst();
cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Toast.makeText(getActivity(), cNumber, Toast.LENGTH_SHORT).show();
nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
for (int i = 0; i < N; i++) {
final TextView rowTextView = new TextView(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
params.setMargins(0,0,0,10);
resultTextView = new TextView[N];
rowTextView.setTextSize(34);
rowTextView.setHeight(140);
rowTextView.setGravity(Gravity.CENTER);
rowTextView.setBackgroundColor(Color.parseColor("#7d3f98"));
rowTextView.setTextColor(Color.WHITE);
//rowTextView.setBackgroundResource(R.drawable.corn);
addItems.addView(rowTextView);
resultTextView[i] = rowTextView;
resultTextView[i].setLayoutParams(params);
if(resultTextView[i] != null ){
resultTextView[i].setText(nameContact+ " "+ cNumber);
}
resultTextView[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String res1 = rowTextView.getText().toString();
System.out.println("num " + res1.length());
res1 = res1.split(" ")[res1.split(" ").length - 1];
startDialActivity(res1);
}
private void startDialActivity(String result) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+result));
startActivity(intent);
}
});
}
}
}
}}}}

Try google PreferenceActivity, you don't have to,you can just use the traditional way(SharedPreference sp =new ....)
, but I think SharedPreferenceActivity is very easier, it's native,very simple and powerfull!

You can make a JSONArray and add name and phone number by making JSONObject and add these JSONObjects to the JSONArray.
JSONObject mainObject=null;
try{
mainObject=new JSONObject();
JSONArray arr = new JSONArray();
for (int i = 0; i < 10; i++) {
JSONObject objName = new JSONObject();
JSONObject objPhone = new JSONObject();
objName.put("name", new String("abbcc"));
objPhone.put("phone", new String("dfdfgdf"));
arr.put(i,objName);
arr.put(i,objPhone);
}
mainObject.put("mainObj",arr);
System.out.println(mainObject.toString());
}
catch(Exception e){
}
shared.edit().putString("details",mainObject.toString()).commit();
and then get string from sharedPreferences wherever you want and the get details from JSONObject and JSONArray

Related

how to get all values of particular TextView of listView? -Android

i have made ListView with three columns 'item','qty','rate' i get this entries from the user and i have made the listview work perfectly but i want to get all the values of the 'rate' column and add them for the net amount.
Here is my android code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
populateList();
adapter = new listviewAdapter(List.this, list);
lview.setAdapter(adapter);
}
private void populateList() {
HashMap temp = new HashMap();
list = new ArrayList<HashMap>();
item = etItem.getText().toString();
qty = etQty.getText().toString();
rate = etRate.getText().toString();
temp.put(FIRST_COLUMN, "1");
temp.put(SECOND_COLUMN, item);
temp.put(THIRD_COLUMN, qty);
temp.put(FOURTH_COLUMN, rate);
list.add(temp);
}
I tried out this method below but it only toast the first value.But i want to get all the values under the rate column and add them up for the net-amount.
public void get() {
StringBuilder sb = new StringBuilder();
for(int i=0; i<adapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.FourthText)).getText().toString();
adapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
}
text = sb.toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
I think this might help you.
private int GrandTotal(ListView list) {
int sum=0;
for (int i = 0; i < list.getCount(); i++) {
View v = list.getChildAt(i);
TextView rate = (TextView) v.findViewById(R.id.rate);
sum = sum + Integer.parseInt(rate.getText().toString() )
}
return sum;
}
:)
public void getTotalRate() {
int totalRate = 0;
for (int i = 0; i < list.size(); i++) {
HashMap temp = list.get(i);
/// here fourth column is rate
int rate = (int) temp.get(FOURTH_COLUMN);
totalRate = totalRate + rate;
}
Toast.makeText(getApplicationContext(), "total rate=" + totalRate, Toast.LENGTH_LONG).show();
}

EditText array of existing EditTexts won't be declared right

I am creating an app, in which I create some EditTexts dynamically with ID number.
I want to pass the information from the EditTexts, so I tried to create a EditText array with these and then use the .getText().toString() to save them in a String Array, which I want pass to the next activity.
It seems like it won't create the "editArray[]" in second code part correctly.
Thanks in advance.
Here's my code (EnterNames.java) - Creation of EditTexts -> Succesful
protected void NumberOfEditText()
{
View VertLayout = (LinearLayout) findViewById(R.id.VertLayout);
String SpinValue = getIntent().getExtras().getString("SpinValue");
int intSpinValue = Integer.valueOf(SpinValue);
editTextCount = intSpinValue;
EditText[] editTextArray = new EditText[editTextCount];
for (int i = 0; i < editTextCount; i++)
{
String Name = "Name " + (i+1);
editTextArray[i] = new EditText(this);
editTextArray[i].setId(i+1000);
editTextArray[i].setText(Name);
editTextArray[i].setTextSize(20);
editTextArray[i].setFilters( new InputFilter[] { new InputFilter.LengthFilter(15) } );
editTextArray[i].setSelectAllOnFocus(true);
editTextArray[i].setSingleLine(true);
editTextArray[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
((LinearLayout) VertLayout).addView(editTextArray[i]);
}
}
Second code (EnterNames.java) - Passing data to next activity -> Failure.
By testing I think the problem is the for-loops (the editArray returns null)
public void Go(View view)
{
setContentView(R.layout.activity_enter_names);
String NameArray [] = new String [editTextCount];
EditText editArray [] = new EditText [editTextCount];
Intent intent = new Intent(this, RandomGeneration.class);
for (int i = 0; i < editTextCount; i++)
{
editArray[i] = (EditText) findViewById(i+1000);
}
for (int i = 0; i < editTextCount; i++)
{
NameArray[i] = editArray[i].getText().toString();
}
Bundle extras = new Bundle();
extras.putInt("NumberofNames", editTextCount);
extras.putStringArray("NameArray", NameArray);
intent.putExtras(extras);
startActivity(intent);
}
According to Activity.findViewById() documentation, this method will search for views in your XML, not in views added in Java.
The simple way to do what you want:
class EnterNames extends Activity {
private int editTextCount;
private EditText[] editTextArray;
protected void NumberOfEditText() {
LinearLayout vertLayout = (LinearLayout) findViewById(R.id.VertLayout);
editTextCount = Integer.valueOf(getIntent().getExtras().getString("SpinValue"));
editTextArray = new EditText[editTextCount];
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
for (int i = 0; i < editTextCount; i++) {
String Name = "Name " + (i+1);
editTextArray[i] = new EditText(this);
editTextArray[i].setText(Name);
editTextArray[i].setTextSize(20);
editTextArray[i].setFilters( new InputFilter[] { new InputFilter.LengthFilter(15) } );
editTextArray[i].setSelectAllOnFocus(true);
editTextArray[i].setSingleLine(true);
editTextArray[i].setLayoutParams(params);
vertLayout.addView(editTextArray[i]);
}
}
[…]
public void Go(View view)
{
// This will delete views added to your LinearLayout, don't use it!
//setContentView(R.layout.activity_enter_names);
String nameArray[] = new String[editTextCount];
for (int i = 0; i < editTextCount; i++) {
nameArray[i] = editArray[i].getText().toString();
}
Bundle extras = new Bundle();
extras.putInt("NumberofNames", editTextCount);
extras.putStringArray("NameArray", nameArray);
Intent intent = new Intent(this, RandomGeneration.class);
intent.putExtras(extras);
startActivity(intent);
}
}
Why you are calling setContentView(R.layout.activity_enter_names); in public void Go(View view)? You overide Activities layout in which you previously has added EditText views and all your findById() returns null.
Your code should work if you remove setContentView(R.layout.activity_enter_names); from Go function.
setContentView(R.layout.activity_enter_names); should be called single time in Activities onCreate function.

java.lang.NumberFormatException: unable to parse '' as integer

i want to set the calculation result in TextView named total[] from the value of EditText named point[] .but i am able to parse the value and put it in the TextView . it give me an error in logcat
06-27 02:27:01.467: E/AndroidRuntime(275): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
this is an error in logcat. i want to add integer values to the textview continuously from the edittext on the same layout
public class player_name extends Activity {
LinearLayout player_name;
TableLayout ply_name;
Bundle b,b1;
List<TextView> allEds = new ArrayList<TextView>();
List<Button> allplus = new ArrayList<Button>();
List<Button> allminus = new ArrayList<Button>();
List<EditText> alledit = new ArrayList<EditText>();
List<TextView> alltotal = new ArrayList<TextView>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
b1 = getIntent().getExtras();
String[] result = b1.getStringArray("playerName");
player_name = (LinearLayout) findViewById(R.id.player_name);
ply_name = new TableLayout(this);
player_name.addView(ply_name);
TableLayout.LayoutParams tableRowParams=new TableLayout.LayoutParams
(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT,1.0f);
TextView[] ed1 = new TextView[result.length+1];
Button[] plus = new Button[result.length+1];
Button[] minus = new Button[result.length+1];
EditText[] point = new EditText[result.length+1];
TextView[] total = new TextView[result.length+1];
TableRow[] TR= new TableRow[result.length+1];
int[] totalscore = null;
String[] temp = null;
Button btnResult = new Button(player_name.this);
btnResult.setText(" click here to get RESULT");
for(int i=0;i<=(result.length-1);i++) {
ed1[i] = new TextView(player_name.this);
plus[i] = new Button(player_name.this);
minus[i] = new Button(player_name.this);
point[i] = new EditText(player_name.this);
total[i] = new TextView(player_name.this);
TR[i] = new TableRow(player_name.this);
allEds.add(ed1[i]);
alltotal.add(total[i]);
alledit.add(point[i]);
allplus.add(plus[i]);
allminus.add(minus[i]);
TR[i].addView(ed1[i]);
TR[i].addView(point[i]);
TR[i].addView(plus[i]);
TR[i].addView(minus[i]);
TR[i].addView(total[i]);
ply_name.addView(TR[i]);
TR[i].setLayoutParams(tableRowParams);
totalscore[i] =Integer.parseInt(point[i].getText().toString());
temp[i] = "" + totalscore[i];
ed1[i].setId(i);
ed1[i].setHeight(50);
ed1[i].setWidth(70);
ed1[i].setText(result[i]);
ed1[i].setTextColor(Color.CYAN);
total[i].setId(i);
total[i].setHeight(50);
total[i].setWidth(70);
total[i].setText(""+0);
total[i].setTextColor(Color.CYAN);
point[i].setId(i);
point[i].setHeight(50);
point[i].setWidth(120);
point[i].setHint(result[i]+"\'s");
point[i].setInputType(InputType.TYPE_CLASS_NUMBER);
point[i].setTextColor(Color.BLACK);
plus[i].setId(i);
plus[i].setHeight(50);
plus[i].setWidth(50);
plus[i].setText("+");
plus[i].setTextColor(Color.BLACK);
minus[i].setId(i);
minus[i].setHeight(50);
minus[i].setWidth(50);
minus[i].setText("-");
minus[i].setTextColor(Color.BLACK);
plus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
minus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
player_name.addView(btnResult, lp);
btnResult.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent1 = new Intent(player_name.this,result.class);
startActivity(intent1);
}
});
}
}
You need to check whether the string you are parsing is an integer. Try this code:
if (IsInteger(point[i].getText().toString()))
totalscore[i] =Integer.parseInt(point[i].getText().toString());
and add this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
I hope this helps

Saving Android Preferences

Hi, I have a listview and i'm wanting it so that when you press on an item it stores your selection in shared preferences. The purpose for this is so that next time I open the app it skips the selection process.
So what I'm wanting to know is how do I incorporate this function into my code?
Here is my code so far:
public class SelectTeamActivity extends ListActivity {
public String fulldata = null;
public String position = null;
public String divisionName= null;
public List<String> teamsList = null;
public String divName = null;
protected void loadData() {
fulldata = getIntent().getStringExtra("fullData");
position = getIntent().getStringExtra("itemIndex");
Log.v("lc", "selectteamActivity:" + fulldata);
Log.v("lc", "position:" + position);
int positionInt = Integer.parseInt(position);
try{
JSONObject obj = new JSONObject(fulldata);
teamsList = new ArrayList<String>();
JSONObject objData = obj.getJSONObject("data");
JSONArray teamInfoArray = objData.getJSONArray("structure");
for(int r = 0; r < teamInfoArray.length(); r++ ){
JSONObject teamFeedStructureDict = teamInfoArray.getJSONObject(r);
JSONArray teamStructureArray =
(JSONArray) teamFeedStructureDict.get("divisions");
JSONObject teamFeedDivisionsDictionary =
teamStructureArray.getJSONObject(positionInt);
divName = teamFeedDivisionsDictionary.getString("name");
JSONArray teamNamesArray =
(JSONArray) teamFeedDivisionsDictionary.get("teams");
for(int t = 0; t < teamNamesArray.length(); t++){
JSONObject teamNamesDict = teamNamesArray.getJSONObject(t);
teamsList.add(teamNamesDict.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selectact);
loadData();
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText(divName);
TextView redHeaderText = (TextView) findViewById(R.id.redheadertext);
redHeaderText.setText("Please select your team:");
setListAdapter( new ArrayAdapter<String>(this, R.layout.single_item,
teamsList));
ListView list = getListView();
list.setTextFilterEnabled(true);
}
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
Intent intent = new Intent(this, HomeActivity.class);
String curPos = Integer.toString(position);
//or just use the position:
intent.putExtra("itemIndex", curPos);
intent.putExtra("fullData", fulldata); //or just the part you want
startActivity(intent);
}
}
In your Activity's onCreate():
SharedPreferences preferences = getSharedPreferences("preferences", MODE_WORLD_WRITEABLE);
In your onListItemClick():
preferences.edit().putInt("KEY", position).commit();
Everywhere in your project:
int position = preferences.getInt("KEY", -1);
(-1 is a default value that means when there is no value with the given key, return this value)

How to get tablerow id dynamically in android?

Hello, my old code is working, but the problem is that when i am clicking tablerow it call another activty, but it not set that table row data but it setting last array data to that activity.
Means it set the last array value to next screen activity.
for ( j = 0; j < dataListfeture.size(); j++)
{
HashMap<String, String> hm = new HashMap<String, String>();
hm = dataListfeture.get(j);
final TableRow tblrow = new TableRow(MainScreen.this);
final View rowView = inflater.inflate(R.layout.featuredrow, null);
tblrow.setId(j);
tblrow.getId();
featuredName = (TextView) rowView.findViewById(R.id.xxName);
featuredDistance = (TextView) rowView.findViewById(R.id.xxDistance);
featuredVeneType = (TextView) rowView.findViewById(R.id.xxVeneType);
featuredPhone = (TextView) rowView.findViewById(R.id.xxPhone);
featuredAddress = (TextView) rowView.findViewById(R.id.xxAddress);
Drawable image = ImageOperations(MainScreen.this, hm.get("url"), "image.jpg");
featuredImage = (ImageView) rowView.findViewById(R.id.xxdImage);
featuredImage.setImageDrawable(image);
featuredName.setText("" + hm.get("name"));
featuredDistance.setText("" + hm.get("distance") + " mi");
featuredVeneType.setText("" + hm.get("venuetype"));
featuredPhone.setText("" + hm.get("phonenumber"));
featuredAddress.setText("" + hm.get("address"));
mapnamelist = hm.get("name");
mapvenuelist = hm.get("venuetype");
mapothervenuelist = hm.get("othervenuetype");
mapaddresslist= hm.get("address");
mapcitylist= hm.get("city");
mapstatelist= hm.get("state");
tblrow.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
final ProgressDialog progDailog = ProgressDialog.show(MainScreen.this, null, "Loading ....", true);
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
System.out.println("search");
Intent myIntent = new Intent(MainScreen.this, xxxxscreen.class);
startActivity(myIntent);
MainScreen.this.finish();
progDailog.dismiss();
}
};
new Thread()
{
public void run()
{
try
{
System.out.println();
handler.sendEmptyMessage(1);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}.start();
}
});
Create an int array of id say array_id[] and after setting id to table row add that id to array_id[] also like
tblrow.setId(j);
array_id[j] = j;
And in onClick method do this:
for(int i = 0;i< array_id.length;i++)
{
TableRow tbl_row = (TableRow) findViewById(i);
if(v.getId() == array_id[i])
{
/** Perform your Operations */
}
}

Categories

Resources