Setting outer class variable from anonymous inner class - java

Hey guys i am trying to export data from a third party app and then set the path of resulting exported file to my textview in main activity.But it isn't working.I searched all over and came to a conclusion that it has something to do with anonymous class,but i am still not able to fix it.Can anyone please guide me.
public class MyActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btRecieve = (Button) findViewById(R.id.btRecieve);
final Context context = this.getApplicationContext();
final TextView tvFilePath = (TextView) findViewById(R.id.tvFilepath);
final TextView tvFeedBack = (TextView) findViewById(R.id.tvFeedBack);
final String pDateFrom = "2012-07-01";
final String pDateTo = "2012-07-06";
final String pExportType = "e5";
final String pExportFormat = "csv";
btRecieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TimeRecordingExport exporter = new TimeRecordingExport(pDateFrom,pDateTo,pExportType,pExportFormat,tvFilePath);
exporter.Export(context);
String path = exporter.getFilePath();
tvFilePath.setText(path);
}
});
}
}
public class TimeRecordingExport{
//private variables
String mDateFrom;
String mDateTo;
String mExportType;
String mExportFormat;
private String mFilepath; //path to the output file
String feedback;
TextView mTv;
File file;
Context mContext;
final String KEY_RESULT_FILE = "com.dynamicg.timerecording.FILE";
//Constructor
public TimeRecordingExport(String pDateFrom,String pDateTo,String pExportType,String pExportFormat,TextView tv){
//Initialize private variables
mDateFrom = pDateFrom;
mDateTo = pDateTo;
mExportFormat = pExportFormat;
mExportType = pExportType;
mTv = tv;
} //End constructor
//Export function
public void Export(Context pContext){
mContext = pContext;
//create a new intent with action export
Intent intent = new Intent("com.dynamicg.timerecording.DATA_EXPORT");
//Add extra values or you could say parameters to this intent.
intent.putExtra("com.dynamicg.timerecording.DATE_FROM",mDateFrom);
intent.putExtra("com.dynamicg.timerecording.DATE_TO",mDateTo);
intent.putExtra("com.dynamicg.timerecording.EXPORT_TYPE",mExportType);
intent.putExtra("com.dynamicg.timerecording.EXPORT_FORMAT",mExportFormat);
//make a broadcast reciever
BroadcastReceiver resultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent resultIntent) {
Bundle bundle = this.getResultExtras(true);
TimeRecordingExport.this.mFilepath = bundle.getString(KEY_RESULT_FILE); //Path to the created file
//mTv.setText(mFilepath[0]);
file = new File(mFilepath); //New Created file
feedback = "File=["+file+"], canRead=["+file.canRead() //Info about the created file
+"], sizeKB=["+(file.length()/1024)+"]";
//Toast.makeText(mContext, feedback, Toast.LENGTH_LONG).show();
Toast.makeText(context, feedback, Toast.LENGTH_LONG).show();
System.out.println(feedback);
}
};
mContext.sendOrderedBroadcast(intent, null, resultReceiver, null, Activity.RESULT_OK, null, null);
} //End function export
public String getFilePath(){
return mFilepath;
}
public String getFileInfo(){
return feedback;
}
} //End of class

First, have you tried putting a test string in for the path value? Just to be sure it's not your data? Second, guess I've always defined my widgets as class variables of the Activity instead of final variables in the onCreate method.

Related

Calling Class to another activity

I have a second activity that handles all the user input and another activity that handles all the data from the second activity. What I want to do is call a class "SubmitName" from the activity to the second activity so that I dont need to pass the values from second activity to the main activity anymore. Here are the codes..
MainActivity (Where the class "SubmitName" are located and values are passed.)
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView Name;
String lastname;
String licensenumber;
String mviolation;
String maplace;
String maddress;
String phonenumber;
String officername;
String contactnumber;
String datetime;
RecyclerView.LayoutManager layoutManager;
RecyclerAdapter adapter;
ArrayList<Violator> arrayList = new ArrayList<>();
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBtn = (Button)findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FragActivity.class);
startActivity(intent);
}
});
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
Name = (TextView) findViewById(R.id.tvName);
Intent intent = getIntent();
String str = intent.getStringExtra("firstname");
lastname = intent.getStringExtra("lastname");
licensenumber = intent.getStringExtra("licensenumber");
mviolation = intent.getStringExtra("violation");
maplace = intent.getStringExtra("arrestplace");
maddress = intent.getStringExtra("address");
phonenumber = intent.getStringExtra("phonenumber");
contactnumber = intent.getStringExtra("contactnumber");
officername = intent.getStringExtra("officername");
datetime = intent.getStringExtra("datetime");
Name.setText(str);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
readFromLocalStorage();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
readFromLocalStorage();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.TrafficAd:
Intent i = new Intent(this, TrafficAdvisory.class);
this.startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
public void submitName(View view)
{
String name = Name.getText().toString();
String lname = lastname;
String lnumber = licensenumber;
String violation = mviolation;
String aplace = maplace;
String address = maddress;
String pnumber = phonenumber;
String cnumber = contactnumber;
String oname = officername;
String dtime = datetime;
saveToAppServer(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime);
Name.setText("");
}
public void readFromLocalStorage()
{
arrayList.clear();
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = dbHelper.readFromLocalDatabase(database);
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
String lname = cursor.getString(cursor.getColumnIndex(DBContract.LNAME));
String lnumber = cursor.getString(cursor.getColumnIndex(DBContract.LNUMBER));
String violation = cursor.getString(cursor.getColumnIndex(DBContract.VIOLATION));
String aplace = cursor.getString(cursor.getColumnIndex(DBContract.ARRESTPLACE));
String address = cursor.getString(cursor.getColumnIndex(DBContract.ADDRESS));
String pnumber = cursor.getString(cursor.getColumnIndex(DBContract.PNUMBER));
String cnumber = cursor.getString(cursor.getColumnIndex(DBContract.CNUMBER));
String oname = cursor.getString(cursor.getColumnIndex(DBContract.ONAME));
String dtime = cursor.getString(cursor.getColumnIndex(DBContract.DTIME));
int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
arrayList.add(new Violator(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,sync_status));
}
adapter.notifyDataSetChanged();
cursor.close();
}
public void saveToAppServer(final String name,final String lname, final String lnumber,final String violation, final String aplace,final String address, final String pnumber, final String cnumber, final String oname, final String dtime)
{
if (checkNetworkConnection())
{
StringRequest stringRequest = new StringRequest(Request.Method.POST,DBContract.SERVER_URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if(Response.equals("OK"))
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_OK);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
} catch (JSONException e){
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name",name);
params.put("lname",lname);
params.put("lnumber",lnumber);
params.put("violation", violation);
params.put("aplace", aplace);
params.put("address",address);
params.put("pnumber",pnumber);
params.put("cnumber",cnumber);
params.put("oname",oname);
params.put("dtime",dtime);
return params;
}
}
;
MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
}
SecondActivity (Where inputs are handled and data passing to the mainactivity)
public class ViolatorDetail extends AppCompatActivity implements View.OnClickListener{
EditText Name;
Button btnClose;
TextView DTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violator_detail);
DTime = (TextView)findViewById(R.id.tvDTime);
final String currentDT = DateFormat.getDateTimeInstance().format(new Date());
DTime.setText(currentDT);
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(this);
Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText Name = (EditText)findViewById(R.id.etfName);
EditText LName = (EditText)findViewById(R.id.etlName);
EditText LNumber = (EditText)findViewById(R.id.etlNumber);
EditText Violation = (EditText)findViewById(R.id.etViolation);
EditText Arrestplace = (EditText)findViewById(R.id.etaPlace);
EditText Address = (EditText)findViewById(R.id.etAddress);
EditText PNumber = (EditText)findViewById(R.id.etpNumber);
EditText CNumber = (EditText)findViewById(R.id.etcNumber);
EditText OName = (EditText)findViewById(R.id.etoName);
String DT = DTime.getText().toString();
Intent intent = new Intent(ViolatorDetail.this, MainActivity.class);
intent.putExtra("firstname", Name.getText().toString());
intent.putExtra("lastname", LName.getText().toString());
intent.putExtra("licensenumber", LNumber.getText().toString());
intent.putExtra("violation", Violation.getText().toString());
intent.putExtra("arrestplace", Arrestplace.getText().toString());
intent.putExtra("address", Address.getText().toString());
intent.putExtra("phonenumber", PNumber.getText().toString());
intent.putExtra("contactnumber", CNumber.getText().toString());
intent.putExtra("officername", OName.getText().toString());
intent.putExtra("datetime", DT);
startActivity(intent);
}
});
}
}
What I want to do is call the "SUBMITNAME" class to the second activity so that no data passing will be done anymore.
As other friends mentioned Intent is a correct and good way to transfer data between activities. But if you want to avoid writing so much code to transfer data I suggest to create a pure java class (or java bean) and define all needed fields in that class (note: this class should implement java.io.Serializable interface). Now you could transfer instances of this class between activities.
I don’t think there is a better way of passing data between activities than Intents.
What you probably need is encapsulation of passing of extra. You can achieve this by making a static method in the ViolatorDetail class, which accepts as arguments as values you would like to pass, and returns Intent.
public static Intent newIntent(Context packageContext, String ... args){
Intent intent = new Intent(packageContext, ViolatorDetail.this);
intent.putExtra(EXTRA_STRING_ARGS, args);
return intent;
}
Then in the caller class you make an intent by makeing a static call on that function, and pass values as arguments
Intent intent = ViolatorDetail.newIntent(getActivity(), strings)
startActivity(intent);
However, in your case, you should probably make a more sensible way of passing data than as array of strings.
If you don't want to pass data between Activities with Intent, you can do it by writing certain data in a file and when you need it just read from it... I did it like this and I'm still happy i did it that way, it's simple and relatively quick, you just have to care a little about IOExceptions.

Android Studio saving data in database

I'm new here, and also new to Android Studio.
My first project is to create a diary to save a users workouts.
I'm having trouble saving for this data..
Here is my front page for the app. With the button "Styrkeboken" (Strengthbook) I'll be entering my sets, reps, weight(vikt) and excercise(övning). I want to save this data in the second button "Historik" (History), but I can't manage it to work as I want to..
Code from my class "Pass" (Workout):
package com.example.mama0086.styrkeboken;
public class Pass {
private int _set;
private int _reps;
private float _vikt;
private String _övning;
public Pass() {
}
public Pass(int set, int reps, float vikt, String övning) {
this._set = set;
this._reps = reps;
this._vikt = vikt; //Vikt = weight
this._övning = övning; //Övning = excercise
}
public void set_set(int _set) {
this._set = _set;
}
public void set_reps(int _reps) {
this._reps = _reps;
}
public void set_vikt(float _vikt) {
this._vikt = _vikt;
}
public void set_övning(String _övning) {
this._övning = _övning;
}
public int get_set() {
return _set;
}
public int get_reps() {
return _reps;
}
public float get_vikt() {
return _vikt;
}
public String get_övning() {
return _övning;
}
}
Code from my class "Historik" (History):
public class Historik extends AppCompatActivity {
EditText editSet;
TextView textSet;
EditText editReps;
TextView textReps;
EditText editVikt;
TextView textVikt;
EditText editÖvning;
TextView textÖvning;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historik);
editSet = (EditText) findViewById(R.id.editSet);
textSet = (TextView) findViewById(R.id.textSet);
editReps = (EditText) findViewById(R.id.editReps);
textReps = (TextView) findViewById(R.id.textReps);
editVikt = (EditText) findViewById(R.id.editVikt);
textVikt = (TextView) findViewById(R.id.textVikt);
editÖvning = (EditText) findViewById(R.id.editÖvning);
textÖvning = (TextView) findViewById(R.id.textÖvning);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add excercise
public void addBtn(View view){
Pass pass = new Pass(textSet.getText().toString()); //Pass is swedish for work-out
dbHandler.addPass(pass);
printDatabase();
}
public void removeBtn(){
String inputText = textSet.getText().toString();
dbHandler.deletePass(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.historikToString();
textSet.setText(dbString);
editSet.setText("");
textReps.setText(dbString);
editReps.setText("");
textVikt.setText(dbString);
editVikt.setText("");
textÖvning.setText(dbString);
editÖvning.setText("");
}
}
In the "Historik" class I get this error message:
"Cannot resolve constructor 'Pass(java.lang.String)'
please let me know if you need the code for my database.
I appreciate the help!
You defined 2 different constructors for your Pass class :
public Pass() {
}
public Pass(int set, int reps, float vikt, String övning) {
this._set = set;
this._reps = reps;
this._vikt = vikt; //Vikt = weight
this._övning = övning; //Övning = excercise
}
However in your Historik activity, you're trying to instantiate a new Pass with a String only as a parameter Pass pass = new Pass(textSet.getText().toString());
You will need to change this line to match one of the 2 constructors you have, or define a 3rd one taking only a String as argument
EDIT : Depending on your Pass object, you can either :
declare a 3rd constructor taking only a String (I assume it's övning)
public Pass(String övning) {
this._övning = övning;
}
if the textSet.getText().toString() is not relevant, simply use the default constructor Pass pass = new Pass();

How do I iteratively add to a List on button click in java?

I want to add values to an array/list and then store these in shared preferences, to then display on another activity.
When I try my code it only seems to save the first value, and if I add more it just overwrites the value.
I do not want to create the List each time I click the button so I have put it at the very beginning.
If there isn't an existing value then the message should be added to the List and stored in shared preferences as Status_0, if there is an existing value then it should be added as Status_1 - but it's not. I think it is because it is not saving properly in the List but I'm not sure how to do that.
Here's my code:
public class EnterReadingsActivity extends AppCompatActivity implements View.OnClickListener {
private EditText erTemperatureEditText;
private Button erSubmitBtn;
public List<String> values = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_enterreadings);
init();
}
private void init() {
erTemperatureEditText = (EditText) findViewById(R.id.erTemperatureEditText);
erSubmitBtn = (Button) findViewById(R.id.erSubmitBtn);
erSubmitBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId()==R.id.erSubmitBtn) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String message = erTemperatureEditText.getText().toString();
editor.putInt("Status_size", values.size());
int status_size = values.size();
for (int i = status_size; i < status_size + 1; i++) {
editor.putString("Status_" + i, message);
values.add(message);
editor.commit();
}
}
}
}
Edit:
int status_size = values.size();
for(int i = 0; i < status_size + 1; i++)
{
String value = values.get(i);
if (value != null) {
values.add(value);
status_size++;
String textView_i = "textView" + i;
TextView textView_i = new TextView(this);
textView_i.setLayoutParams(new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT));
textView_i.setText(value);
historyBackgroundInside.addView(textView_i);
}
}
It is incorrect to use the sharedPreferences to pass data from one activity to another.
The data are usually entered into an object (Bundle) which will be passed in the intent and then taken up in the next activity.
another way is to use the extras that works like Bundle
public class EnterReadingsActivity extends AppCompatActivity implements View.OnClickListener {
private EditText erTemperatureEditText;
private Button erSubmitBtn;
public List<String> values = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_enterreadings);
init();
}
private void init() {
erTemperatureEditText = (EditText) findViewById(R.id.erTemperatureEditText);
erSubmitBtn = (Button) findViewById(R.id.erSubmitBtn);
erSubmitBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId()==R.id.erSubmitBtn) {
String message = erTemperatureEditText.getText().toString();
values.add(message);
}
//Here you should enter the condition that allows you to
//call the method to go to the next activity
//ex: click of a button, I have the list reaches a size
//Add a example code
if (values.size() == 10) {
passDataAndGoInAnotherActivity();
}
}
public void passDataAndGoInAnotherActivity () {
Intent i = new Intent (this, NameOfYouNextActivity.class);
i.putExtra("status_list", values);
// Or use Bundle
// Bundle bundle = new Bundle();
// bundle.putSerializable("status_list", values);
// i.putExtra("bundle", values)
startActivity(i)
}
}
to take in the other activity values using this code
public class NameOfYourNextActivity extends AppCompatActivity {
public List<String> values;
public ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_nameoflayout);
listview = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
//If you first method
if (intent != null && intent.hasExtra("status_list")) {
List<String> values = (List<String>)intent.getSerializableExtra("status_list")
}
//If you second method (Bundle)
// if (intent != null && intent.hasExtra("Bundle")) {
// Bundle bundle = intent. getBundleExtra("Bundle")
// if (bundle != null && bundle.containsKey("status_list")) {
// List<String> values = (List<String>)intent.getSerializableExtra(String name)
// }
if (values != null) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listview.setAdapter(adapter);
}
}
}
I did the update of the code to give you a solution that comes close to what you need..
Remember to create the next activity and insert it in the manifest.
Change the name of the class based on your activity and enter the correct layout name.
Remember to include in your layout a list view (change id in my code) that will allow you to print your values.
In this example it uses a simple adapter with a layout provided by Android, but you can create something custom.
Here you will find an excellent guide

Cannot pass two strings from one activity to another activity at same time

I have two activities Select and Upload. I am passing two strings id and scan_id from one activity to another. The value passes correctly when I pass the id alone. But when I try to pass both the values the one value overrides the other value. Is there a separate way to pass the two strings???
SelectActivity.java
public class SelectActivity extends Activity {
String v1;
public static String EXTRA_MESSAGE_ID;
public static String EXTRA_MESSAGE_SCAN;
int flag;
String strflag;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll()
.build();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
Bundle b = getIntent().getExtras();
EditText ed=(EditText)findViewById(R.id.patient_id);
ed.setText(b.getCharSequence("Contents"));
Button button = (Button) findViewById(R.id.button1);
StrictMode.setThreadPolicy(policy);
Button CTbutton = (Button) findViewById(R.id.CTScan);
CTbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=1;
strflag = String.valueOf(flag);
Log.e("log_tag", "sel id"+flag);
Log.e("log_tag", "sel scan"+v1);
Intent intent = new Intent(SelectActivity.this,MainActivity.class);
intent.putExtra(EXTRA_MESSAGE_ID,v1);
intent.putExtra(EXTRA_MESSAGE_SCAN,strflag);
startActivity(intent);
}
});
}
}
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
private Button btnCapturePicture;
public static String EXTRA_MESSAGE_ID;
public static String EXTRA_MESSAGE_SCAN;
String message_id;
String message_scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
Intent intent = getIntent();
message_id = intent.getStringExtra(SelectActivity.EXTRA_MESSAGE_ID);
message_scan = intent.getStringExtra(SelectActivity.EXTRA_MESSAGE_SCAN);
Log.e("log_tag", "id"+message_id);
Log.e("log_tag", "scan"+message_scan);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
}
}
The logcat looks like this:
04-01 10:57:43.671: E/log_tag(12649): connection success
04-01 10:57:50.374: E/log_tag(12649): sel id1
04-01 10:57:50.374: E/log_tag(12649): sel scan2
04-01 10:57:50.403: E/log_tag(12649): id1
04-01 10:57:50.403: E/log_tag(12649): scan1
initialize the strings in both activity with same values
public static String EXTRA_MESSAGE_ID="something1";
public static String EXTRA_MESSAGE_SCAN="something2";
Your logic is correct but problem in below code
public static String EXTRA_MESSAGE_ID;
public static String EXTRA_MESSAGE_SCAN;
you don't have assign the value to a both variable. so by default both variable have blank value. so when you put the value, the second one will overwrite it. because both varable same key as blank value
So, try to use give unique value to a variable.
public static String EXTRA_MESSAGE_ID = "MSG_ID";
public static String EXTRA_MESSAGE_SCAN = "MSG_SCAN";
I hope you understand.
You should try like this:
Change in SelectActivity:
public static String EXTRA_MESSAGE_ID="ExtraMsgId";
public static String EXTRA_MESSAGE_SCAN="ExtraMsgScan";
Should not do like this. If you give like this
public static String EXTRA_MESSAGE_ID;
public static String EXTRA_MESSAGE_SCAN;
This is look like empty string.

Call a "void" method that have values from another activity

Hi I'm quite new to Java, I wonder how to call a void method from another activity, when I already moved to new activity. For example, I want to call
onCreate(Bundle state)
from PocketSphinxActivty.java
in my new activity SMSReaderMain.java
I already tried
PocketSphinxActivity ps = new PocketSphinxActivity();
ps.onCreate(null);
It gives no error, but when SMSReaderMain.java activity start it suddenly force close and not responding in the actual device.
I also try to change into ps.onCreate(this) or ps.onCreate(SMSReaderMain.this) but it gives
The method setupRecognizer(File) in the type PocketSphinxActivity is not applicable for the arguments
(SMSReaderMain)
Here's the complete code, and I want to call almost all of method there in my new activity SMSReaderMain.java
PocketSphinxActivity.java
package edu.cmu.pocketsphinx.demo;
public class PocketSphinxActivity extends Activity implements
RecognitionListener {
//keyword yang digunakan dalem program untuk set ke even2 tertentu
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "drive mode";
private static final String MENU_SEARCH = "menu";
private static final String KEYPHRASE = "ok";
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Buat nyiapin User Interface
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
//captions.put(DIGITS_SEARCH, R.string.digits_caption);
captions.put(FORECAST_SEARCH, R.string.forecast_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
//nyocokin keyword dan pindah2 menu
#Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
try {
Intent i= null;
if (text.equals(KEYPHRASE)) {
switchSearch(MENU_SEARCH);
}
if (text.equals(DIGITS_SEARCH)) {
//panggil class SMSReaderMain
recognizer.stop();
i = new Intent(getApplicationContext(),SMSReaderMain.class);
startActivity(i);
}
if (text.equals(FORECAST_SEARCH)) {
switchSearch(FORECAST_SEARCH);
}
//else
//((TextView) findViewById(R.id.result_text)).setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}
//nge pop up keyword yang sesuai kita ucapin sama library yg udah ada
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
//kembali ke menu utama
/*#Override
public void onEndOfSpeech() {
if (DIGITS_SEARCH.equals(recognizer.getSearchName())
|| FORECAST_SEARCH.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}**/
//nampilin caption yg di mau sesuai dengan keyword
public void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
//inisiasi recognizer di awal
public void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create grammar-based searches.
File menuGrammar = new File(modelsDir, "grammar/mulai.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
//File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
//recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
}
#Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
}
}
SMSReaderMAin.java
public class SMSReaderMain extends Activity {
private final int CHECK_CODE = 0x1;
private final int LONG_DURATION = 5000;
private final int SHORT_DURATION = 1200;
private Speaker speaker;
private ToggleButton toggle;
private OnCheckedChangeListener toggleListener;
private TextView smsText;
private TextView smsSender;
private BroadcastReceiver smsReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//PocketSphinxActivity ps = new PocketSphinxActivity();
//ps.setupRecognizer(null);
//ps.onPartialResult(null);
//ps.onResult(null);
//ps.switchSearch(null);
setContentView(R.layout.main_sms);
//recognizer.startListening(searchName);
toggle = (ToggleButton)findViewById(R.id.speechToggle);
smsText = (TextView)findViewById(R.id.sms_text);
smsSender = (TextView)findViewById(R.id.sms_sender);
toggleListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if(isChecked){
speaker.allow(true);
speaker.speak(getString(R.string.start_speaking));
}else{
speaker.speak(getString(R.string.stop_speaking));
speaker.allow(false);
}
}
};
toggle.setOnCheckedChangeListener(toggleListener);
checkTTS();
initializeSMSReceiver();
registerSMSReceiver();
}
private void checkTTS(){
Intent check = new Intent();
check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(check, CHECK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CHECK_CODE){
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
speaker = new Speaker(this);
}else {
Intent install = new Intent();
install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(install);
}
}
}
private void initializeSMSReceiver(){
smsReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle!=null){
Object[] pdus = (Object[])bundle.get("pdus");
for(int i=0;i<pdus.length;i++){
byte[] pdu = (byte[])pdus[i];
SmsMessage message = SmsMessage.createFromPdu(pdu);
String text = message.getDisplayMessageBody();
String sender = getContactName(message.getOriginatingAddress());
speaker.pause(LONG_DURATION);
speaker.speak("You have a new message from" + sender + "!");
speaker.pause(SHORT_DURATION);
speaker.speak(text);
smsSender.setText("Message from " + sender);
smsText.setText(text);
}
}
}
};
}
private void registerSMSReceiver() {
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
}
private String getContactName(String phone){
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor.moveToFirst()){
return cursor.getString(0);
}else {
return "unknown number";
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
speaker.destroy();
}
}
This is a really wrong approach to the way of programming in Android. Activities are one of the main core components in an Android application that is managed directly by the OS, which means that the system creates them and are managed by the OS. The onCreate method is part of the lifecycle and it is automatically called by the system. Here you have the activity's lifecycle.
The way of starting a new activity is:
Intent intent = new Intent(mContext, MyActivity.class);
startActivity(intent);
As the activity is instanciated by the system, you cannot call directly to methods on it. The way of communicating between activities is by providing bundle objects in the intent, so in the new Activity you can get the data from:
getIntent().getExtras()
You can also provide backward information by using startActivityForResult instead of startActivity, receiving a result in onActivityResult.
You have the info you need here.
Activity corresponds to something you are going to display on screen. If you are not going to display anything, don't create activities.
In this example you do not need PocketsphinxActivity at all. You can move all the methods of PocketsphinxActivity into your SMSReaderMain activity.
If you want to separate speech recognition code into separate class you can create a separate PocketsphinxRecognizer class but inherit it from Object, not from the Activity.

Categories