How to store received data in an array? - java

I am working on an Android application which receives data from an RFDuino and displays it on a Line Chart.
In my Mainactivity, the broadcastReceiver sends data into a method addData on receiving.
private final BroadcastReceiver rfduinoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (RFduinoService.ACTION_CONNECTED.equals(action)) {
upgradeState(STATE_CONNECTED);
} else if (RFduinoService.ACTION_DISCONNECTED.equals(action)) {
downgradeState(STATE_DISCONNECTED);
} else if (RFduinoService.ACTION_DATA_AVAILABLE.equals(action)) {
addData(intent.getByteArrayExtra(RFduinoService.EXTRA_DATA));
}
}
};
The addData method is as follows:
public void addData(byte[] data) {
View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_2, dataLayout, false);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
String riz = HexAsciiHelper.bytesToHex(data);
t1 = Integer.parseInt(riz, 16);
String testString = String.valueOf(t1);
text1.setText(testString);
dataLayout.addView(view,LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
}
Now, I want to store value of t1 into an array. The problem is that when I try to do it, a NullPointerException occurs and the program stops.
Any help would be appreciated.

Declare ArrayList<Integer> and Store the t1 value after doing null check.
ArrayList <Integer> t1array = new ArrayList <Integer> ();
String riz = HexAsciiHelper.bytesToHex(data);
if (riz != null) {
Integer t1 = t1 = Integer.parseInt(riz, 16);
t1array.Add(t1);
}

Related

Edit values and update in firebase

this time i want to edit and update the new values in Firebase Database. I have read the firebase documentation and followed the steps. https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields
i need a litte orientation, following the documentation's steps i have modifed my POJO class,
as proof just add the interno key in the public Map<>...
public class Cow implements Serializable {
String interno;
public Cow() {
}
public Cow(String interno) {
this.interno = interno;
}
public String getInterno() {
return interno;
}
public void setInterno(String interno) {
this.interno = interno;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("inte", interno);
return result;
}
}
This is my database in firebase
I have a recyclerview and I send the values to another activity by an intent, where i show the details, in this detailcow i want to modify the values.
This is the code:
public class Cowdetail extends AppCompatActivity {
DatabaseReference reference;
EditText tvinterno, tvsiniiga, tvpadre, tvmadre, tvnacimiento, tvinseminacion, tvtoro, tvestatus, tvnotas;
AppCompatImageView tvimage;
Button tvbutton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailcow);
tvinterno = (EditText) findViewById(R.id.tvinterno);
tvsiniiga = (EditText) findViewById(R.id.tvsiniiga);
tvpadre = (EditText) findViewById(R.id.tvpadre);
tvmadre = (EditText) findViewById(R.id.tvmadre);
tvnacimiento = (EditText) findViewById(R.id.tvnacimiento);
tvinseminacion = (EditText) findViewById(R.id.tvinsemincion);
tvtoro = (EditText) findViewById(R.id.tvtoro);
tvestatus = (EditText) findViewById(R.id.tvestatus);
tvnotas = (EditText) findViewById(R.id.tvnotas);
tvimage = (AppCompatImageView) findViewById(R.id.tvimage);
tvbutton = findViewById(R.id.actualizar);
String vpadre = "";
String vmadre = "";
String vinterno = "";
String vsiniiga = "";
String vnacimiento = "";
String vinseminacion = "";
String vtoro = "";
String vestatus = "";
String vnotas = "";
String vurl;
Bundle extras = getIntent().getExtras();
if (extras !=null);
vinterno = extras.getString("keyint");
vsiniiga = extras.getString("keysin");
vmadre = extras.getString("madre");
vpadre = extras.getString("padre");
vnacimiento = extras.getString("nacimiento");
vinseminacion = extras.getString("inseminacion");
vtoro = extras.getString("toro");
vestatus = extras.getString("estatus");
vnotas = extras.getString("notas");
String image = extras.getString("img");
if (image == null|| image.isEmpty()){
tvimage.setImageResource(R.drawable.ic_imageinf);
} else {
Picasso.get().load(image).fit().centerCrop().into(tvimage);
}
tvpadre.setText(vpadre);
tvinterno.setText(vinterno);
tvsiniiga.setText(vsiniiga);
tvmadre.setText(vmadre);
tvnacimiento.setText(vnacimiento);
tvinseminacion.setText(vinseminacion);
tvtoro.setText(vtoro);
tvestatus.setText(vestatus);
tvnotas.setText(vnotas);
tvbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Update();
}
});
}
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("inte", tvinterno);
ref.updateChildren(updates);
}
}
I have added a button to the layout, it has to save the edited values to firebase with the public void Update, Im doing something wrong, but in my short (almost nil) experience i can't see the error. also, i'm looking for a asesor who can guide me in my project, if someone want to talk about it, send me an email to: pjcm97#outlook.com
Firebase Realtime Database stores JSON data. You're trying to write an EditText object to it, which is not JSON data. So your code is most likely crashing.
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("inte", tvinterno.getText().toString());
ref.updateChildren(updates);
}
I also highly recommend always checking the result of a write operation, to see if it succeeded, as shown in the documentation on adding a completion listener.

How to use an `Arraylist` in `OnClick` method?

When I try to use an ArrayList, and StringBuffer in OnClick method, Android studio wants me to change them to final. But when I do that, I can only keep the last inserted element in ArrayList.
SharedPreferences sp = mContext.getSharedPreferences("checked",Context.MODE_PRIVATE);
final SharedPreferences.Editor e=sp.edit();
final ArrayList<Integer> sharedP= new ArrayList<>();
final String word = words.get(position).getMean();
final int id= words.get(position).getId();
final StringBuffer str= new StringBuffer("");
holder.rowText.setText(word);
holder.rowText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.rowText.isChecked()) {
sharedP.remove(sharedP.indexOf(id));
holder.rowText.setCheckMarkDrawable(null);
holder.rowText.setChecked(false);
} else {
sharedP.add(id);
holder.rowText.setCheckMarkDrawable(R.drawable.ic_check_black_24dp);
holder.rowText.setChecked(true);
}
for(int i=0;i<sharedP.size();i++){
Log.e("sharedpreference1",sharedP.get(i).toString());
str.append(sharedP.get(i));
}
e.putString("str", str.toString());
e.commit();
}
});
Updated code
SharedPreferences sp = mContext.getSharedPreferences("checked",Context.MODE_PRIVATE);
e=sp.edit();
sharedP= new ArrayList<>();
word = words.get(position).getMean();
Log.e("getMean",word);
id= words.get(position).getId();
str= new StringBuffer("");
holder.rowText.setText(word);
holder.rowText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.rowText.isChecked()) {
sharedP.remove(sharedP.indexOf(word));
flag=false;
holder.rowText.setCheckMarkDrawable(null);
holder.rowText.setChecked(false);
} else {
sharedP.add(word);
flag=true;
Log.e("deneme",word);
holder.rowText.setCheckMarkDrawable(R.drawable.ic_check_black_24dp);
holder.rowText.setChecked(true);
}
str.delete(0,str.length());
for(int i=0;i<sharedP.size();i++){
Log.e("sharedpreference1",sharedP.get(i).toString());
str.append(sharedP.get(i));
str.append(".");
}
if(flag==false){
e.remove("str");
e.commit();
}
Log.e("size",str.toString());
e.putString("str", str.toString());
e.remove("set");
e.commit();
}
});
but it still returns the last element of Array
example of checkedTextView
shared preference
You have to declare your variables outside of that method.
private SharedPreferences.Editor e;
private ArrayList<Integer> sharedP= new ArrayList<>();
private String word = null;
private int id= 0;
private StringBuffer str = null;
Then:
e=sp.edit();
sharedP= new ArrayList<>();
word = words.get(position).getMean();
id= words.get(position).getId();
str= new StringBuffer("");
Declare the Arraylist and the String Buffer as global variables.
private ArrayList<Integer> sharedP = new ArrayList<>();
private StringBuffer str = new StringBuffer("");

Retrieve data from a List

Sorry if the heading is misleading, i couldn't quite put it in words.
Rotten Tomatoes
The list runs fine and looks fine for what i am doing. What i am planning on doing is have a details page now with the synopsis etc. I thought about passing the ID of the movie that is passed on.
If i click on a movie, how can i, in the next page set the image of that movie, the text etc. Basically get all the data i need from the selected movie?
The source code can be found here - Github
Screenshot (Terrible looking but its just messing around):
Thanks
I was having the same problemm in my project but your seems similar so i will give you my solution in order to help.
In my case i was retrieving stocks from a database and each stock had extra 15 prices which i wanted to show everytime i tapped on a stock so check the below answer.
Code:
I created an OBject with String[] to help me retrieve all those 15 prices for each stock and then pass it through Intent.
public class StockList {
private String stockCurrentName;
private String stockCurrentPrice;
private String stockImage;
private String[] restPrices;
public StockList(String stockCurrentName, String stockCurrentPrice, String stockImage, String[] restPrices) {
this.stockCurrentName = stockCurrentName;
this.stockCurrentPrice = stockCurrentPrice;
this.stockImage = stockImage;
this.restPrices = restPrices;
}
public String getStockCurrentName() {
return stockCurrentName;
}
public void setStockCurrentName(String stockCurrentName) {
this.stockCurrentName = stockCurrentName;
}
public String getStockCurrentPrice() {
return stockCurrentPrice;
}
public void setStockCurrentPrice(String stockCurrentPrice) {
this.stockCurrentPrice = stockCurrentPrice;
}
public String getStockImage() {
return stockImage;
}
public void setStockImage(String stockImage) {
this.stockImage = stockImage;
}
public String[] getRestPrices() {
return restPrices;
}
public void setRestPrices(String[] restPrices) {
this.restPrices = restPrices;
}
}
Then is how i retrieved the data:
public class JsonReadTask extends AsyncTask<String, Void, String> {
public JsonReadTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListLoaderActivity.this);
pDialog.setTitle(R.string.waiting);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage(getString(R.string.get_stocks));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrawer();
pDialog.dismiss();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[]{url});
}
public void ListDrawer() {
customList = new ArrayList<StockList>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//for each stock i get its prices.
//In your List for each movie you can get its synopsis and anything else you need.
name = jsonChildNode.optString("name");
price = jsonChildNode.optString("price");
price1 = jsonChildNode.optString("price1");
price2 = jsonChildNode.optString("price2");
price3 = jsonChildNode.optString("price3");
price4 = jsonChildNode.optString("price4");
price5 = jsonChildNode.optString("price5");
price6 = jsonChildNode.optString("price6");
price7 = jsonChildNode.optString("price7");
price8 = jsonChildNode.optString("price8");
price9 = jsonChildNode.optString("price9");
price10 = jsonChildNode.optString("price10");
price11 = jsonChildNode.optString("price11");
price12 = jsonChildNode.optString("price12");
price13 = jsonChildNode.optString("price13");
price14 = jsonChildNode.optString("price14");
price15 = jsonChildNode.optString("price15");
image = jsonChildNode.optString("image");
justPrices = new String[]{price1, price2,
price3, price4, price5, price6, price7, price8, price9,
price10, price11, price12, price13, price14, price15};
loipesTimes = new String[]{"1st Day Value " + price1, "2nd Day Value " + price2, "3rd Day Value " + price3, "4th Day Value " + price4, "5th Day Value " + price5,
"6th Day Value " + price6, "7th Day Value " + price7, "8th Day Value " + price8, "9th Day Value " + price9,
"10th Day Value " + price10, "11th Day Value " + price11, "12th Day Value " + price12, "13th Day Value " + price13, "14th Day Value " + price14, "15th Day Value " + price15};
customList.add(new StockList(name, price, image, justPrices));
}
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
ArrayAdapter adapter = new MyStocksAdapter(ListLoaderActivity.this, R.layout.list_item, customList);
adapter.notifyDataSetChanged();
startList.setAdapter(adapter);
}
And then pass the through Intent
private void registerCallClickBack() {
startList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
tv1 = (TextView) viewClicked.findViewById(R.id.stock_name);
tv2 = (TextView) viewClicked.findViewById(R.id.stock_price);
Intent intent = new Intent(ListLoaderActivity.this, StockItem.class);
intent.putExtra("name", tv1.getText().toString());
intent.putExtra("price", tv2.getText().toString());
intent.putExtra("stockInfo", customList.get(position).getRestPrices());
intent.putExtra("stockImage", customList.get(position).getStockImage());
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
}
I guess you can use it like this and this will help you get it done!!!
Hope i helped you!!!
if you show us what are you doing in your code we could help you more but to pass data from one activity to another you can use intent example :
String value= getIntent().getStringExtra("keyName");
Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
intent.putExtra("keyName", value);
startActivity(intent);
You should do something like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
YourObject item = arraylist.get(arg2);
TextView textView = (TextView) arg1.findViewById(R.id.textView);
Intent intent = new Intent(ThisActivity.this, SecondActivity.class);
intent.putExtra("textview_value", textView.getText().toString());
startActivity(intent);
}
}
});
you can use intent for pass data from one activity to another exactly how Moudiz say and then retrieve received data like this
String value;
Intent intent = getIntent();
value = intent.getStringExtra("keyName");
If you would have pasted your code then it would be easier to understand your actual problem . But with the data and json given :
1.if you having problem in retrieving data from Json then please follow below link :
http://www.androidhive.info/2012/01/android-json-parsing-tutorial
If passing to next Activity then it would be done using Intent:
String value= getIntent().getStringExtra("Key");
Intent intent = new Intent(this, DataClassNameHere.class);
intent.putExtra("key", value);
startActivity(intent);

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.

what is the use of this handler while writing android code?

Here in the below code a songsManager object is created and then why is this.songsList used to store the song files and why not only songsList is used. Main question is what is the use of this and what exactly is it and when it is used?
My main doubt is that here since no other songsList is declared so there is no chance of songsList clashing so why to specifically refer to it as the songsList declared in the present class. Mainly I use it when there are arguments passed to a function whose names are same as that of objects or variables declared within the class so to avoid confusion and to tell the compiler that I want to use the object declared in that class and not the one passed as an argument I used this.. Please correct me if I am wrong and add to my knowledge about this.
The code lines of interest are followed by //
please see to it
public class CustomizedListView extends Activity{
private int currentIndex;
private String[] menuItems = {"Play","Share Music Via","Details"};
private LinkedList<File> songsList = new LinkedList<File>();//
private ArrayList<HashMap<String, String>> songsListdata = new ArrayList<HashMap<String, String>>();
private MediaMetadataRetriever mmr = new MediaMetadataRetriever();
private Utilities utils=new Utilities();
ListView list=null;
ModifiedAdapter adapter=null;
SongsManager plm=null;//
Button search;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
plm = new SongsManager();//
File extStore = Environment.getExternalStorageDirectory();
// get all songs from sdcard
this.songsList = plm.getFilesInFolder(extStore);//
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = new HashMap<String, String>();
mmr.setDataSource(songsList.get(i).getAbsolutePath().toString());
//getting artist
String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST);
if(artist==null)
artist=mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
//getting Duration
String len = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long Len=0;
try
{
Len=Integer.parseInt(len);
}
catch(Exception e)
{
Log.i(null, ":conversion error");
}
len=utils.milliSecondsToTimer(Len);
Log.i(null, "length"+len);
song.put("songTitle", (songsList.get(i)).getName().substring(0, ((songsList.get(i)).getName().length() - 4)));
song.put("songArtist", artist);
song.put("duration", len);
song.put("songPath",songsList.get(i).getAbsolutePath().toString());
// adding HashList to ArrayList
songsListdata.add(song);
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new ModifiedAdapter(this, songsListdata);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
final String songPath =songsList.get(position).getAbsolutePath().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(CustomizedListView.this);
builder.setTitle((songsList.get(position)).getName().substring(0, ((songsList.get(position)).getName().length() - 4)));
builder.setItems(menuItems, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
if(item==0)
{
Intent in = new Intent(getApplicationContext(),MainActivity.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", position);
setResult(100, in);
// Closing PlayListView
finish();
}
else if(item==2)
{
Intent details = new Intent(getApplicationContext(),Details.class);
details.putExtra("songPath", songPath);
startActivity(details);
}
else if(item==1)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("audio/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(songPath)));
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
//Search for a song implementations
search=(Button)findViewById(R.id.searchForSong);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent launchBrowser=new Intent(getApplicationContext(), Browser.class);
startActivity(launchBrowser);
}
});
}
}
Actually this answer should be broken in a few steps
1
THIS operator
it will refer to the current object/scope in which it is used
for eg:
say a button listener is made like this
new button(context).setOnClickListener(new View.onClickListener(public void onClick(View v){
//Using this here to refers to this onclicklistener
});
// for a constructor
public classname(int arg1){
//so to initialise the arg1 of yur class with this arg1
//for just thesake of.clarity you write
this.arg1=arg1;
}
2
this used here with the songlist is redundant and is of no signficance as ther e is no conflict.
Hope this helps you.
this keyword is used to refere to the current object
So you can access any member of current object using this.member. As in your example you are accesig songList within the current object so there is no difference between using this and not using this.
More use of this keyword
as you mentioned about the following example
private int a;
void method(int a){
this.a = a;
}
here this is used to refer to the member of current object as the names are same. if you used
void method(int b){
a = b;
}
then there would be no difference between using this and not using this
Some More Example
private int a = 5;
public void method() {
int a = 6;
System.out.println(a); // will print 6
System.out.println(this.a); // will print 5
}
int the following example the second one is pointing to the member variable of current object so it is printing 5.

Categories