call a contact/existing number from an app - android

i am programming for android an app and i want to call a random phone number from this app... so i got this, that you can enter a contact and his number is going to be saved in sharedPreferences.. dont know for what but it looks cool :D.. now i am trying to call the latest contact which the user added, but i dont know how to do that... i already copied much code of other questions in my programm without success...
hope you can help me adding a call function
ummm... ya i copied nearly the whole code.. so dont ask me pls what for some statements are... (i wont have anything against an explenation)
package com.example.getcontacts;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final String EXTRA_MESSAGE = "com.example.getcontacts";
private TextView tv;
private int i = loadI();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
load(tv, i);
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.pick_person)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
//get all saved phone numbers
((Button)findViewById(R.id.allNr)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent inte = new Intent(null, Contacts.class);
inte.putExtra(EXTRA_MESSAGE, i);
startActivity(inte);
}
});
}
//doing random sh*t which i dont know whaat happens
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
//get some datas... ?
Uri uri = data.getData();
if (uri != null) {
//get more data
Cursor c = null;
try {
//initializing something
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
//initializing phone number
String number = c.getString(0);
//get the type... somehow
int type = c.getInt(1);
//save in shared preferences and show the latest nr
int i = save(number);
showSelectedNumber(type, number);
load(tv, i);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, "Saved Nr : " + number, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public String load(TextView tv, int i) {
String sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
String c = Integer.toString(i);
sharedNumber = sp.getString(c, "");
tv.setText("Number: " + sharedNumber);
return sharedNumber;
}
public int save(String value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
int i = 0;
String c;
c = Integer.toString(i);
edit.putString(c, value);
edit.commit();
i =Integer.parseInt(c);
i++;
saveI("savedI", i);
return i;
}
public void saveI(String key, int value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putInt(key, value);
edit.commit();
}
public int loadI() {
int sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
sharedNumber = sp.getInt("savedI", 0);
return sharedNumber;
}
}

Related

Not saving String value in sharedPreferences

I am trying to save a string in sharedPreferences. I don't know what I did wrong but it doesn't save the String value.
this is the code
here I am saving String value "phone". notice its Fragment page
package com.world.bolandian.watchme;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
public class LoginFragment extends Fragment implements Listen {
Button loginBtn;
ServerRequest ser;
Connector c;
LoginCommunicationThread loginT;
private LoginUser logUser;
EditText phone,password;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
}
public void setInterface(Connector c){
this.c=c;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ser=new ServerRequest();
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOGIN_SERVLET);
ser.setResponse(this);
loginT = new LoginCommunicationThread(ser);
phone = (EditText)getActivity().findViewById(R.id.userTxt);
password = (EditText)getActivity().findViewById(R.id.passwordTxt);
loginBtn = (Button) getActivity().findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//save phone number in sharedpreferences
SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putString("PHONE",String.valueOf(phone.getText()));
edt.commit();
Context context = getActivity();
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("PHONE", String.valueOf(phone.getText()));
logUser = new LoginUser(phone.getText().toString(),password.getText().toString());
if (phone.getText().toString() == null)
{
Toast.makeText(getActivity(),"Please enter phone number", Toast.LENGTH_LONG).show();
}
if(password.getText().toString() == null)
{
Toast.makeText(getActivity(),"Please enter password", Toast.LENGTH_LONG).show();
}
else {
Gson g = new Gson();
String ans = g.toJson(logUser, LoginUser.class);
login(logUser);
}
}
});
}
public void login (LoginUser user)
{
LoginCommunicationThread con;
ServerRequest ser = new ServerRequest();
ser.setResponse(this);
Gson gson = new Gson();
String send = gson.toJson(user,LoginUser.class);
ser.addParamaters(Params.USER,send);
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOGIN_SERVLET);
con = new LoginCommunicationThread(ser);
con.start();
}
#Override
public void good() {
Toast.makeText(getActivity(), "Welcome", Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(),MainActivity.class);
startActivity(i);
}
#Override
public void notGood() {
Toast.makeText(getActivity(),"Wrong password or phone",Toast.LENGTH_LONG).show();
}
#Override
public void notGoodServerEroorr() {
Toast.makeText(getActivity(), "Connection Error please try again", Toast.LENGTH_LONG);
}
}
Here i extract the value "PHONE" but i keep getting null. for some reason it doesnt get the value and the default is null (This page is Activity)
package com.world.bolandian.watchme;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import com.google.gson.Gson;
public class MainActivity extends Activity implements Listen {
private LockAndUnLock sendnotf;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView)findViewById(R.id.status);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabspec = tabHost.newTabSpec("main");
tabspec.setContent(R.id.main);
tabspec.setIndicator("Main");
tabHost.addTab(tabspec);
tabspec = tabHost.newTabSpec("gps");
tabspec.setContent(R.id.GPS);
tabspec.setIndicator("GPS");
tabHost.addTab(tabspec);
tabspec = tabHost.newTabSpec("info");
tabspec.setContent(R.id.INFO);
tabspec.setIndicator("Info");
tabHost.addTab(tabspec);
}
public void Lock (View view)
{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
String phone = sharedPreferences.getString("PHONE", null);
PreferenceManager.getDefaultSharedPreferences(this).getString("PHONE",
null);
sendnotf = new LockAndUnLock(phone,1); // 1 = true = lock
Gson g = new Gson();
String ans=g.toJson(sendnotf, LockAndUnLock.class);
sendLockAndUnlock(sendnotf);
if (status.getVisibility() != View.VISIBLE) {
status.setVisibility(View.VISIBLE);
}
status.setText("LOCKED");
status.setTextColor(Color.RED);
}
public void UnLock (View view)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String phone = sharedPreferences.getString("PHONE",null);
sendnotf = new LockAndUnLock(phone,0); // 0 = false = unlock
Gson g = new Gson();
String ans=g.toJson(sendnotf, LockAndUnLock.class);
sendLockAndUnlock(sendnotf);
if (status.getVisibility() != View.VISIBLE) {
status.setVisibility(View.VISIBLE);
}
status.setText("OPEN");
status.setTextColor(Color.GREEN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void good() {
}
#Override
public void notGood() {
}
#Override
public void notGoodServerEroorr() {
}
public void sendLockAndUnlock(LockAndUnLock sendnotf){
RegisterCommunicationThread con;
ServerRequest ser = new ServerRequest();
ser.setResponse(this);
Gson gson = new Gson();
String send = gson.toJson(sendnotf, LockAndUnLock.class);
ser.addParamaters(Params.LOCKANDUNLOCK,send);
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOCKANDUNLOCK_SERVLET);
con = new RegisterCommunicationThread(ser);
con.start();
}
}
Problem is with different shared preferences objects. According to official documentation:
getPreferences (int mode)
Added in API level 1 Retrieve a SharedPreferences object for accessing
preferences that are private to this activity. This simply calls the
underlying getSharedPreferences(String, int) method by passing in this
activity's class name as the preferences name.
My suggestion is to use special entity for handling shared preferences. In your case it may look like following code
public class SharedPreferencesManager {
private static final String PREFERENCES_NAME = "your_name";//name for xml file
private final SharedPreferences sharedPreferences;
public SharedPreferencesManager(Context context) {
sharedPreferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public String getPhone() {
return sharedPreferences.getString("PHONE", null);
}
public void savePhone(#NonNull String phone) {
sharedPreferences.edit().putString("PHONE", phone).apply(); //or commit for blocking save
}
}
Then replace all your direct call to SharedPreferences in Activity, Fragment with above object.

Two activities sending data to each other

Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detais_rest, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quentity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);

android save contacts and call them

i am programming a little bit android and i have a problem with adding and calling contacts.
my idea was to add two contacts and when the call-button was pressed the user can decide which one he wants to call.. and my two problems are, that on my AVD the code is working until i have to call somebody. so i can choose 2 contacts and these contacts are safed... on the phone of my friend i cant even choose contacts.. the programm just says: "The Application Contacts_SPrefs stopped working"...
well i think there is a problem in my code.. but i dont know where it is and how i could fix it, because in my previous version the code works...
So in this part of the app you can add 2 contacts and choose the button call which opens the other intent which is described below
Main Activity
package com.example.contact_sprefs;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private String contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.bro1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
//-------- > this thing here opens the contacts view < ------
//later its waiting until the user clicks on a number of his contacts
contact = "Brah1";
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.bro2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contact = "Brah2";
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.call)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), OpenMenu.class);
startActivity(intent);
}
});
}
//doing random sh*t which i dont know whaat happens
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
//after he clicked a number its getting to this point
//in the uri it saves some number and all this things where the contact is
//so this is for the location
Uri uri = data.getData();
if (uri != null) {
//get more data
//in this cursor all the values of the contacts are going to be safed
//c is for the contact
Cursor c = null;
try {
//here all datas from the contact are going to be safed in c
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
//c is the phone number in very special code types and stuff like that
//in c is everything from the contact saved
//now c is going to be converted into a string -> everything that stays is the phone number
String number = c.getString(0);
//get the type... somehow
int type = c.getInt(1);
showSelectedNumber(type, number);
save(contact, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, "Saved Nr : " + number, Toast.LENGTH_LONG).show();
}
public void save(String type, String number) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(type, number);
edit.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
so.. as you can see.. i dont know really much about the topic Intent and its specifications.. anyway... heres the second part of the app, in which the call-command is.. and this command doesent work either...
OpenMenu
package com.example.contact_sprefs;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class OpenMenu extends Activity {
private String nr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_menu);
((Button)findViewById(R.id.bro1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
nr = load("Brah1", nr);
String uri = "tel:" + nr.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
((Button)findViewById(R.id.bro2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
nr = load("Brah2", nr);
String uri = "tel:" + nr.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
}
public void showSelectedNumber(String number) {
Toast.makeText(this, "Took Nr : " + number, Toast.LENGTH_LONG).show();
}
public String load(String brahNr, String number) {
String sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
sharedNumber = sp.getString(brahNr, number);
return sharedNumber;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.get
ItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
....well... this is a lot of code(for me).. and i thank everybody who helps me :)
edited lateron
i just forgot the permissions... so this is also needed
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
vZ

Android Voice input without click

I am new to android development. I need a solution for the new app I am developing which takes voice input and gives output in voice by mapping with a mapping database. Current program takes voice input with onlick on button . I need a soultion which can take voice input without clicking of any button simliar to Talking Tom application . Here is my code.My main code is in speakToMe which is method called on onclick & onActivityResult
package com.example.secondprog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import com.example.secondprog.*;
//import com.example.secondprog.DatabaseHelper;
public class MainActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST = 0;
//private static final int VOICE_RECOGNITION_REQUEST = 0x10101;
TextToSpeech ttobj;
String resulttxt ;
TestDBClass db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new TestDBClass(this, null, null, 1);
try {
db.loadWords();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ttobj=new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
ttobj.setLanguage(Locale.UK);
Toast.makeText(getApplicationContext(), "No error",
Toast.LENGTH_LONG).show();
}
}
});
//DatabaseHelper db = DatabaseHelper(this);
//dbdtls dbdtlsresult = new dbdtls();
//String message3 = db.getdtls("how are");
//String output = dbdtlsresult.new_name();
//EditText editText = (EditText) findViewById(R.id.edit_message);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.edit_message);
String txt = editText.getText().toString();
// Toast.makeText(getApplicationContext(), txt.toUpperCase(),
// Toast.LENGTH_LONG).show();
DictonaryDAO dictonaryDAO =
db.findname(txt.toUpperCase());
if (dictonaryDAO != null) {
resulttxt = String.valueOf(dictonaryDAO.getnewname());
Toast.makeText(getApplicationContext(), resulttxt.toUpperCase(),
Toast.LENGTH_LONG).show();
}
ttobj.speak(resulttxt, TextToSpeech.QUEUE_FLUSH, null);
}
/*#Override
public void onPause(){
if(ttobj !=null){
ttobj.stop();
ttobj.shutdown();
}
super.onPause();
}
*/
**public void speakToMe(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Please speak slowly and enunciate clearly.");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST && resultCode == RESULT_OK) {
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// TextView textView = (TextView) findViewById(R.id.speech_io_text);
String firstMatch = matches.get(0);
// textView.setText(firstMatch);
DictonaryDAO dictonaryDAO =
db.findname(firstMatch.toUpperCase());
if (dictonaryDAO != null) {
resulttxt = String.valueOf(dictonaryDAO.getnewname());
Toast.makeText(getApplicationContext(), resulttxt.toUpperCase(),
Toast.LENGTH_LONG).show();
ttobj.speak(resulttxt, TextToSpeech.QUEUE_FLUSH, null);
}
}
}**
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Voice Recognition not working for talking tom app so you try to use noise detection with sound meter. below here link for voice/ noise detection with audio recording without click.
http://androidexample.com/Detect_Noise_Or_Blow_Sound_-_Set_Sound_Frequency_Thersold/index.php?view=article_discription&aid=108&aaid=130
Please change SoundMeter.java File
mRecorder.setOutputFile(Environment.getExternalStorageDirectory().
getAbsolutePath() + "/test.3ggp");

android crash when trying to get extras.getLong

I have been trying for hours to figure out why android crashes after loading Profile activity. The line that is causing the issue is :
mRowId = extras != null ? extras.getLong(OverLimitDbAdapter.KEY_ROWID): null;
located in Profile.java. so I have firstly
OvertheLimit.java which puts extras via a menu option intent:
package uk.co.obdesign.android.overthelimit;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Overthelimit extends ListActivity {
private OverLimitDbAdapter dbHelper;
private static final int USER_CREATE = 0;
private static final int USER_EDIT = 1;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getListView();
dbHelper = new OverLimitDbAdapter(this);
dbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void fillData() {
cursor = dbHelper.fetchAllUserDrinks();
startManagingCursor(cursor);
String[] from = new String[] { OverLimitDbAdapter.KEY_USERNAME };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.user_row, cursor, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.profile:
Intent myIntent1 = new Intent(Overthelimit.this, Profile.class);
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
startActivityForResult(myIntent1, 0);
return true;
case R.id.myusual:
Intent myIntent2 = new Intent(Overthelimit.this, MyUsual.class);
startActivityForResult(myIntent2, 0);
return true;
case R.id.trackme:
Intent myIntent3 = new Intent(Overthelimit.this, TrackMe.class);
startActivityForResult(myIntent3, 0);
return true;
case R.id.moreinfo:
Intent myIntent4 = new Intent(Overthelimit.this, MoreInfo.class);
startActivityForResult(myIntent4, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
dbHelper.close();
}
}
}
then selecting the profile menu option takes me to Profile, which crashes trying to get extras.
I have checked data using toast and it's there. any ideas?
package uk.co.obdesign.android.overthelimit;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
public class Profile extends Activity{
private EditText mUserName;
private RadioGroup mGender;
private EditText mAge;
private EditText mHeight;
private EditText mWeight;
private Spinner mDrinkerType;
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.profile);
mUserName = (EditText) findViewById(R.id.userName);
mAge = (EditText) findViewById(R.id.age);
mHeight = (EditText) findViewById(R.id.height);
mWeight = (EditText) findViewById(R.id.weight);
mGender = (RadioGroup) findViewById(R.id.gender);
mDrinkerType = (Spinner) findViewById(R.id.drinkerType);
Button next = (Button) findViewById(R.id.NextUsualDrinks);
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(OverLimitDbAdapter.KEY_ROWID)
: null;
}
populateFields();
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
//finish();
Intent myIntent = new Intent(view.getContext(), MyUsual.class);
startActivityForResult(myIntent, 0);
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor todo = mDbHelper.fetchUserDrinks(mRowId);
startManagingCursor(todo);
mUserName.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_USERNAME)));
String gender = todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_GENDER));
// Returns an integer which represents the selected radio button's ID
int selected = mGender.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
String bn = (String) b.getText();
if (bn.equalsIgnoreCase(gender)) {
if(gender == "male")
((RadioButton) findViewById(R.id.male)).setChecked(true);
else if (gender == "female")
((RadioButton) findViewById(R.id.female)).setChecked(true);
}
mAge.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_AGE)));
mHeight.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_HEIGHT)));
mWeight.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_WEIGHT)));
String drinkerType = todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_TYPE));
for (int i = 0; i < mDrinkerType.getCount(); i++) {
String s = (String) mDrinkerType.getItemAtPosition(i);
Log.e(null, s + " " + drinkerType);
if (s.equalsIgnoreCase(drinkerType)) {
mDrinkerType.setSelection(i);
}
}
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String username = mUserName.getText().toString();
// Returns an integer which represents the selected radio button's ID
int selected = mGender.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
String gender = (String) b.getText();
String age = mAge.getText().toString();
String height = mHeight.getText().toString();
String weight = mWeight.getText().toString();
String type = (String) mDrinkerType.getSelectedItem();
if (mRowId == null) {
long id = mDbHelper.createUserProfile(username, gender, age, height, weight, type);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateUserProfile(mRowId, username, gender, age, height, weight, type);
}
}
}
Your problem is most likely that you add a String extra (as cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)) returns a String) - but try to get a Long extra - which does not compute.
The following should fix the problem:
mRowId = extras != null ? Long.parseLong( extras.getString(OverLimitDbAdapter.KEY_ROWID) ) : null;
In your Overthelimit class you set the value with the following line:
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
This puts a String value into the intent extras. Trying to get the same value as a Long value will make you applications crash, as it does not exist as a Long value. If you instead convert the value you get from your cursor object (or gets it directly as a Long from your cursor), your application should not crash anymore. Alternatively, you can get your value from the intent extras by using getString(), not getLong().
I think it giving type casting error as you store the value as string in put try to type cast at putting the value time or get the as string and then convert to long value but for type casting may be you getting type casting error in this so put into the try catch block and see the logcat details to detecting the error
type cast here from string to long or
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID,cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
or get as string here and then type cast from string to long
String s = extras.getString(OverLimitDbAdapter.KEY_ROWID);
mRowId = extras != null ? Long.parseLong(s): null;

Categories

Resources