Get variables from one activity to another - android

I work simple android app for sending sms. I have 2 activities. One is main for sending 2 different messages with 2 different content but messages send to same number. On secund activity i have 3 fields: one is for input number to send messages, and other two are for message content. When I click save button app save user input and go back to main activity. And here start my problem. How can i send users input for number to send messages and messages content to main activity to send sms with saved user input? I am totally beginner with android developing so please help! Here is my MainActivity.java:
package com.example.davor.light;
import android.content.Intent; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.telephony.SmsManager; import
android.telephony.SmsMessage; import android.view.Menu; import
android.view.MenuItem; import android.view.View; import
android.widget.Button; import android.widget.ImageView; import
android.widget.TextView; import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// GUMBI INFORMACIJE
Button ukljuci = (Button) findViewById(R.id.ukljuci);
Button iskljuci = (Button) findViewById(R.id.iskljuci);
Button postavke = (Button) findViewById(R.id.postavke);
final ImageView slika = (ImageView) findViewById(R.id.slika);
// INFORMACIJA O PORUCI
final String broj = "097";
final String ukljuciPoruka = "Uključi";
final String iskljuciPoruka = "Isključi";
// KLIK NA GUMB ISKLJUČI
iskljuci.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(broj, null, iskljuciPoruka, null, null);
Toast.makeText(getApplicationContext(), "Isključeno! poslano na broj " + broj, Toast.LENGTH_LONG).show();
slika.setImageResource(R.drawable.off);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Nemoguće isključiti!",Toast.LENGTH_LONG).show();
}
}
});
postavke.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent PostavkeActivity = new Intent(MainActivity.this,
Postavke.class);
startActivity(PostavkeActivity);
}
});
}
#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);
} }
And here is code for my second activity from witch I want to pull users input to MainActivity:
package com.example.davor.light;
import android.app.Activity; import android.content.Intent; import
android.content.SharedPreferences; import
android.preference.PreferenceManager; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.view.Menu; import android.view.MenuItem; import
android.view.View; import android.widget.Button; import
android.widget.EditText; import android.widget.TextView; import
android.widget.Toast;
public class Postavke extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postavke);
gumbZaPovratak();
SharedPreferences loadSettings = PreferenceManager.getDefaultSharedPreferences(this);
String ucitajBroj = loadSettings.getString("spremiBroj", "");
String ucitajUkljuci = loadSettings.getString("spremiUkljuci", "");
String ucitajIskljuci = loadSettings.getString("spremiIskljuci", "");
final EditText postavkeBroj = (EditText) findViewById(R.id.postavkeBroj);
postavkeBroj.setText(ucitajBroj);
final EditText postavkeUkljuci = (EditText) findViewById(R.id.postavkeUkljuci);
postavkeUkljuci.setText(ucitajUkljuci);
final EditText postavkeIskljuci = (EditText) findViewById(R.id.postavkeIskljuci);
postavkeIskljuci.setText(ucitajIskljuci);
Button spremi = (Button) findViewById(R.id.postavkeSpremi);
spremi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
spremiPostavke("spremiBroj", postavkeBroj.getText().toString());
spremiPostavke("spremiUkljuci", postavkeUkljuci.getText().toString());
spremiPostavke("spremiIskljuci", postavkeIskljuci.getText().toString());
Toast.makeText(getApplicationContext(), "Spremljeno", Toast.LENGTH_LONG).show();
finish();
}
});
}
private void postavkeBroj() {
EditText postavkeBroj = (EditText) findViewById(R.id.postavkeBroj);
}
private void spremiPostavke (String ključ, String vrijednost) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(ključ, vrijednost);
editor.commit();
}
private void gumbZaPovratak(){
Button nazad = (Button) findViewById(R.id.nazad);
nazad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#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_postavke, 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);
} }

You can use startActivityForResult()
You can refer this link:
http://hmkcode.com/android-startactivityforresult/

In Activity1
Intent myIntent = new Intent(this,Activity2.class);
myIntent.putExtra("var", variable_to_pass);
startActivity(myIntent);
In Activity2
Bundle extras = getIntent().getExtras();
if (extras != null) {
intentExtra = extras.getString("var"); // retrieving variable
}

You can add data to an intent like this :
String messageContent = (EditText) findViewById(yourMessageContentId).getText().toString();
String messageNumber = (EditText) findViewById(yourMessageNumberId).getText().toString();
intent.putExtra("com.example.davor.light.MESSAGE_CONTENT", messageContent);
intent.putExtra("com.example.davor.light.MESSAGE_NUMBER", messageNumber);
And then get it on the MainActivity :
Intent intent = getIntent();
String messageNumber = intent.getStringExtra("com.example.davor.light.MESSAGE_NUMBER");
String messageContent = intent.getStringExtra("com.example.davor.light.MESSAGE_CONTENT");

you can send information from one activity to other activity like bellow
Intent postavkeActivity = new Intent(MainActivity.this,
Postavke.class);
Bundle bundle=new Bundle();
bundle.putString(|"messageKey1", "message content1");
bundle.putString(|"messageKey2", "message content2");
postavkeActivity.putExtras(bundle);
startActivity(PostavkeActivity);
in main activity get bundle data like bellow
Bundle b=getIntent.getExtras();
String smsContent=b.getString("messageKey1");

Related

Does data save once you leave an activity android

I have an application that populates a ListView with user input data from another Activity ; however, whenever I enter that data into the second Activity then return to the ListView activity I see it populated with the values I entered. But, if I return to the second activity again, enter the values, and go back to the ListView activity, I see the new values updated but the old ones have disappeared.
Now, I don't know if I'm not updating the listview correctly or if I need to use sqlite databases to store this data or shared preferences in order to update the listview to new data while containing the previous information.
Thanks for any help.
ListActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.personalproject.peter.timerapp.TestingForAlarmData.TestAlarm;
import java.util.ArrayList;
import java.util.List;
public class ListOfAlarms extends ActionBarActivity {
private static final int RESULT = 1000;
List<TestAlarm> alarms = new ArrayList<>();
String title;
int totalTime;
ListView listOfAlarms;
ArrayAdapter<TestAlarm> alarmArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_alarms);
final TextView emptyViewForList = (TextView) findViewById(R.id.emptyTextViewForList);
listOfAlarms = (ListView) findViewById(R.id.listView);
alarmArrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, alarms);
listOfAlarms.setAdapter(alarmArrayAdapter);
// if(listOfAlarms.getCount() <= 0){
// emptyViewForList.setText("No Alarms Currently Available");
// listOfAlarms.setEmptyView(emptyViewForList);
// }
listOfAlarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alarms.get(position);
Intent clockDownActivity = new Intent(ListOfAlarms.this, CountDownAct.class);
clockDownActivity.putExtra("Title", title);
clockDownActivity.putExtra("totalTime", totalTime);
startActivity(clockDownActivity);
}
});
}
#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_list_of_alarms, 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);
}
public void goToFillOut(View view) {
Intent goingToFillOut = new Intent(this, Test.class);
startActivityForResult(goingToFillOut, RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RESULT && resultCode == RESULT_OK){
title = data.getStringExtra("title");
totalTime = data.getIntExtra("totalTime", 0);
alarms.add(new TestAlarm(title, totalTime));
alarmArrayAdapter.notifyDataSetChanged();
}
}
}
SecondActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Test extends ActionBarActivity {
private static final String LOGTAG = "Test.class";
private static final long timeInterval = 1000;
private Button complete;
private EditText titleEditText;
private EditText hourEditText;
private EditText minuteEditText;
private EditText secondEditText;
public static int hour;
public static int minute;
public static int second;
public static String title;
public int actualTimeFiniliazedInMilliSeconds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
titleEditText = (EditText) findViewById(R.id.titleEditText);
hourEditText = (EditText) findViewById(R.id.hourEditText);
minuteEditText = (EditText) findViewById(R.id.minuteEditText);
secondEditText = (EditText) findViewById(R.id.secondEditText);
complete = (Button) findViewById(R.id.completeButton);
}
#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);
}
public void saveTimer(View view) {
if(titleEditText.getText().toString().isEmpty() || hourEditText.getText().toString().isEmpty()
|| minuteEditText.getText().toString().isEmpty() || secondEditText.getText().toString().isEmpty()) {
Toast.makeText(this, "Oops you forgot one", Toast.LENGTH_LONG).show();
return;
}
// complete.setVisibility(View.GONE);
title = titleEditText.getText().toString();
hour = Integer.parseInt(hourEditText.getText().toString().trim());
minute = Integer.parseInt(minuteEditText.getText().toString().trim());
second = Integer.parseInt(secondEditText.getText().toString().trim());
hour *= 3600000;
minute *= 60000;
second *= 1000;
actualTimeFiniliazedInMilliSeconds = hour + minute + second;
Intent intent = new Intent(Test.this, ListOfAlarms.class);
intent.putExtra("title", title);
intent.putExtra("totalTime", actualTimeFiniliazedInMilliSeconds);
setResult(RESULT_OK, intent);
finish();
}
}
Alarm.java
public class TestAlarm {
public String title;
public int totalTime;
public TestAlarm (String title, int totalTime) {
this.title = title;
this.totalTime = totalTime;
}
#Override
public String toString() {
return title;
}
}
It seems like you are replacing new list in listview rather to updating old list of listview.
When you come first time on activity A, you should create one global array list where you add all items which are added by user.
Now, when user go on Activity B and add any item, you should carry out value back to Activity A and add that item in list.
After adding that in list, you should notify data to Adapter. So, here your list will have 2 items and it will show on Activity A 2 items.

Getting Cast Exception Android

I'm creating a simple note app in android. I am basically using two activity classes named as Main Page and Second Activity. I'm storing some data in the shared preferences in second activity and want to use it in my first Activity. I'm storing data in shared preferences as (String,Integer) key-pair. In my main activity class, when i'm getting the value from shared preferences as Integer and compare it with value 0,i'm getting an exception that java.lang.string can't be cast to java.lang.integer. I don't know why this exception is coming. Android studio is not giving me an exception but when i run my app, my app crashes. I have attach the code for reference.
MainActivity class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MainPage extends ActionBarActivity {
Notes notes = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
}
#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_page, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
//Map<String, Integer> notesMap = (Map<String, Integer>)sharedPreferences.getAll();
List<Notes> listNotes = new ArrayList<>();
Map<String, ?> prefsMap = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
if (entry.getValue() == 0){
notes = new Notes();
}
notes.setNoteText(entry.getKey());
listNotes.add(notes);
sharedPreferences.edit().putInt(entry.getKey(),2);
}
NotesArrayAdapter notesArrayAdapter = new NotesArrayAdapter(this,R.layout.list_layout, listNotes);
final ListView listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(notesArrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/**/
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
notes = (Notes) parent.getItemAtPosition(position);
Intent intent = new Intent(MainPage.this, SecondActivity.class);
intent.putExtra("Notes",notes);
startActivity(intent);
}
});
}
#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
switch (item.getItemId()) {
case R.id.new_link:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Notes",(android.os.Parcelable)null);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SecondActivity Class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class SecondActivity extends ActionBarActivity {
public SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
Notes notes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
edit = sharedPreferences.edit();
}
#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_second, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
notes = (Notes)intent.getParcelableExtra("Notes");
EditText editText = (EditText) findViewById(R.id.editText);
if(notes != null){
editText.setText(notes.getNoteText());
}
else{
editText.setText(null);
}
}
#Override
protected void onStop() {
super.onStop();
getIntent().removeExtra(notes.getNoteText());
}
#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();
Intent intent = getIntent();
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.save:
EditText editText = (EditText)findViewById(R.id.editText);
if (notes != null){
edit.putInt(String.valueOf(editText.getText()),1);
}
else{
edit.putInt(String.valueOf(editText.getText()),0);
}
edit.commit();
return true;
case R.id.delete:
if(notes != null){
edit.remove(notes.getNoteText());
edit.commit();
finish();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Notes class that I'm using:
package com.example.prateeksharma.noteballondor;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Dell on 02-06-2015.
*/
public class Notes implements Parcelable {
private String noteText;
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
private Notes(Parcel in) {
noteText = in.readString();
}
public Notes(){
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(noteText);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Notes> CREATOR = new Parcelable.Creator<Notes>() {
#Override
public Notes createFromParcel(Parcel in) {
return new Notes(in);
}
#Override
public Notes[] newArray(int size) {
return new Notes[size];
}
};
}
Can anybody tell me why this error is coming in MainActivity class at this line
if (entry.getValue() == 0)
Thank you..
Try to replace
if ((Integer)entry.getValue() == 0){
With
If((Integer.parseInt( entry.getValue()) ==0){

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

I can't make a button appear (possibly issue with static referencing)

I want to make a button appear in the MenuActivity layout but the deciding if statement is in the CapitalReceiver class. I've tried adding 'static' to various variables but it didn't work. Please help!
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class MenuActivity extends Activity {
String status;
Boolean verified = false;
String textColour = "#000000";
TextView mTvCapital;
ArrayAdapter<String> mAdapter;
Intent mServiceIntent;
CapitalReceiver mReceiver;
IntentFilter mFilter;
String country = "7ec47294ff3d8b74";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_layout);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Button IDButton = (Button) findViewById(R.id.getIt);
Button RefreshButton = (Button) findViewById(R.id.refresh);
long updateTimeMillis = System.currentTimeMillis();
String updateTime = (String) DateFormat.format("hh:mm", updateTimeMillis);
//If application has been submitted//
if(preferences.contains("first_middle_store") & !(verified)) {
status = "Status: Application pending. Last updated: " + updateTime;
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.VISIBLE);
textColour = "#000000";
}
//If application has not been submitted
else {
status = "Status: Application not yet submitted";
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.GONE);
textColour = "#000000";
}
TextView text=(TextView)findViewById(R.id.application_status);
text.setTextColor(Color.parseColor(textColour));
text.setText(status);
Button btnNextScreen = (Button) findViewById(R.id.verify);
//Listening to verify event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(), VerifyActivity.class);
startActivity(nextScreen);
}
});
Button btnNextScreen2 = (Button) findViewById(R.id.how);
//Listening to HowItWorks event
btnNextScreen2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen2 = new Intent(getApplicationContext(), HowItWorksActivity.class);
startActivity(nextScreen2);
}
});
//Listening to IDbutton event
IDButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen3 = new Intent(getApplicationContext(), IDActivity.class);
startActivity(nextScreen3);
}
});
}
#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, 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.menu_layout, container, false);
return rootView;
}
}
public void refresh(View view) {
// Getting reference to TextView
mTvCapital = (TextView) findViewById(R.id.tv_capital);
mTvCapital.setText("hello");
// Creating an intent service
mServiceIntent = new Intent(getApplicationContext(), CapitalService.class);
mServiceIntent.putExtra(Constants.EXTRA_ANDROID_ID, country);
// Starting the CapitalService to fetch the capital of the country
startService(mServiceIntent);
// Instantiating BroadcastReceiver
mReceiver = new CapitalReceiver();
// Creating an IntentFilter with action
mFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Registering BroadcastReceiver with this activity for the intent filter
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, mFilter);
}
// Defining a BroadcastReceiver
private static class CapitalReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String capital = intent.getStringExtra(Constants.EXTRA_APPROVAL);
if(capital == "YES") {
//status = "Status: Application Approved";//
//IDButton.setVisibility(View.VISIBLE);//
}
else if(capital == "NO"){
//status = "Status: Application Denied";//
}
}
}
}
Just glancing over your code, a possible solution (and perhaps not the best) would be to make the ID Button variable global. You would then instantiate it in the onCreate whilst still allowing it to be manipulated in other classes in this MenuActivity.
I hope this helps.

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");

Categories

Resources