Android getAllCellInfo() returns null - java

I'm new to android, and I work on a project that goes to collect all cells information that observed by phone. I have used TelephonyManager.getAllCellInfo() method, but it always returns null.
My Code ::
public class NetworkCoverageActivity extends AppCompatActivity {
private String str;
private TextView TV;
private Button getCellsInfoBtn;
private TelephonyManager TM;
private List<CellInfo> cellInfoList;
private PhoneStateListener PSL;
private int event;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_coverage);
TV = (TextView)findViewById(R.id.iv);
getCellsInfoBtn = (Button)findViewById(R.id.getCellsInfoBtn);
TM = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
PSL = new PhoneStateListener();
event = PSL.LISTEN_CELL_INFO | PSL.LISTEN_CELL_LOCATION;
getCellsInfoBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
TM.listen(PSL, event);
cellInfoList = TM.getAllCellInfo();
if(cellInfoList != null)
TV.append("cellInfoList = null");
else{
...
}
}
});
}
I'm working on android 4.4.2 level 17 and set min API level to 17. and I try to collect information from GSM network.
Also, I added the following permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

I have got the solution of my question. that's replaced getAllCellInfo() function by getNeighboringCellInfo() function, although I am running with android level 17 that should be support getAllCellInfo() function and getNeighboringCellInfo() function should be no longer supported.
Anyway, the following is the solution.
package ayad.bslm.com.networkcoverage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
public class NetworkCoverageActivity extends AppCompatActivity {
private TextView TV;
private TelephonyManager TM;
private List<NeighboringCellInfo> neighboringCellInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_coverage);
TV = (TextView)findViewById(R.id.iv);
Button getCellsInfoBtn = (Button)findViewById(R.id.getCellsInfoBtn);
TM = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
getCellsInfoBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
neighboringCellInfoList = TM.getNeighboringCellInfo();
if(neighboringCellInfoList == null)
TV.setText("neighboringCellInfoList == null\n");
else
TV.setText("There are " + neighboringCellInfoList.size() + " Cells\n");
}
});
}
}

Related

Unknown class 'name'

I am new to Android Studio and trying to get used to it. I have tried to make a trivial app where the user could press a button and a random number would be generated. However, when I used the variables in the code it gave me "unknown class 'get'" and "unknown class 'random'" errors. Code is as follows:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button RollButton = findViewById(id.RollButton);
final TextView resultsTextView = findViewById(id.ResultsTV);
final SeekBar seekBar = findViewById(id.seekBar);
RollButton.setOnClickListener(new onClickListener()
{
Random rnd = new Random(10);
private int random = rnd.nextInt(seekBar.getProgress());
CharSequence get = resultsTextView.getText();
get = String.valueOf(random);
});
}
}
Your OnClickListener looks wrong and you can't use private in this case. So try this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button RollButton = findViewById(id.RollButton);
final TextView resultsTextView = findViewById(id.ResultsTV);
final SeekBar seekBar = findViewById(id.seekBar);
RollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rnd = new Random(10);
int random = rnd.nextInt(seekBar.getProgress());
CharSequence get = resultsTextView.getText();
get = String.valueOf(random);
}
});
}
}

Firebase valueEventListener and RecyclerView adapter's notifyItemChanged not working in the same activity

While trying to build a texting app and I added a Firebase value event listener which is called from onCreate() (...callFirebase() function), all of this looked good to me before I realised my RecyclerView stopped updating itself (..messageAdapter.notifyItemInserted(messageList.size()-1)) when I pressed the send button. And RecyclerView starts working properly as soon as I comment the callFirebase() line in onCreate(). Please look at the code and let me know that I did wrong.
package com.siddhantkushwaha.www.raven;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class chat_room extends AppCompatActivity {
private FloatingActionButton sendButton;
private EditText chatEditText;
private String uid_1;
private String uid_2;
private ArrayList<Message> messageList;
private MessageAdapter messageAdapter;
private RecyclerView recyclerView;
private String threadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Intent intent = getIntent();
uid_1 = intent.getStringExtra("sender");
uid_2 = intent.getStringExtra("receiver");
sendButton = findViewById(R.id.sendButton);
chatEditText = findViewById(R.id.chatEditText);
recyclerView = findViewById(R.id.messageRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
messageList = new ArrayList();
messageAdapter = new MessageAdapter(this, messageList, uid_1);
recyclerView.setAdapter(messageAdapter);
callFirebase();
}
private void callFirebase() {
threadId = null;
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadsList(uid_1) + "/" + uid_2).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() != null) {
threadId = dataSnapshot.getValue().toString();
System.out.println(threadId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
);
}
#Override
protected void onStart() {
super.onStart();
}
public void sendButtonClicked(View view) {
sendMessage();
}
private void sendMessage() {
String text_message = chatEditText.getText().toString();
if(text_message.length() == 0)
return;
messageList.add(new Message(text_message, uid_1, uid_2));
messageAdapter.notifyItemInserted(messageList.size()-1);
recyclerView.smoothScrollToPosition(messageAdapter.getItemCount());
chatEditText.setText("");
if(threadId != null) {
addToThread(new Message(text_message, uid_1, uid_2));
}
else {
createThread(new Message(text_message, uid_1, uid_2));
}
}
private void createThread(Message _message) {
String thread_key = Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadsRoot()).push().getKey();
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadDetails(thread_key)).setValue(new ThreadDetails(uid_1, uid_2));
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadMessageList(thread_key)).push().setValue(_message);
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadsList(uid_1) + "/" + uid_2).setValue(thread_key);
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadsList(uid_2) + "/" + uid_1).setValue(thread_key);
threadId = thread_key;
}
private void addToThread(Message _message) {
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadMessageList(threadId)).push().setValue(_message);
}
}
This is happening because you are assigning a value to the threadId variable inside the onDataChange() method and you trying to use it outside that method. Just declaring a variable as global doesn't solve your problem because onDataChange() method has asynchronous behaviour, which means that is called even before you are trying to get the data from the database. A quick fix would be to use that variable only inside that method, or to use the last part of my answer from this post. I also recommend you see this video.

How do I transform a string from EditText to a character array, to allow audio implementation?

This is my code:
package com.example.pembroke.finalalgorhythmic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button asdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asdf = (Button) findViewById(R.id.keybutton);
asdf.setOnClickListener(MainActivity.this);
}
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
}
What I want to do, is create a character array, so that I can use media player class to play certain sounds based on the user input after my button is clicked. Any ideas?
Have you tried
notes.toCharArray() yet?
EDIT: Long version
EDIT 2: Sample implementation
MediaPlayer mp;
char[] currentNotes;
int noteIndex;
// Create the mp in onCreate and register your onCompletion callback
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
currentNotes = notes.toCharArray();
noteIndex = 0;
mp.setDataSource(getNoteResource(currentNotes[0]));
mp.start();
}
// Convert tone values into
public int getNoteResource(char tone) {…}
#Override
public void onCompletion(MediaPlayer mp) {
if(++noteIndex < currentNotes.length) {
mp.setDataSource(getNoteResource(currentNotes[noteIndex]));
mp.start();
}
}

How to load text to speech in async

I have this code that initializes text to speech. However, text to speech takes around ten seconds to load so I would like it to be done in async. How can I do this without changing the functionality of my code?
import java.util.Locale;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.content.res.Resources;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Button;
import java.lang.String;
import java.util.Random;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener{
TextToSpeech tts;
private static final Random r_generator = new Random();
String textViewString;
int MY_DATA_CHECK_CODE = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Resources res = getResources();
TextView tv = (TextView) findViewById(R.id.animal_text);
String loadingString = res.getString(R.string.Loading);
tv.setText(loadingString);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
int result=tts.setLanguage(Locale.US);
if(result==TextToSpeech.LANG_MISSING_DATA ||
result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("error", "This Language is not supported");
}
Resources res = getResources();
TextView tv = (TextView) findViewById(R.id.animal_text);
String[] myString = res.getStringArray(R.array.englishAnimalArray);
String q = myString[r_generator.nextInt(myString.length)];
tv.setText(q);
textViewString = tv.getText().toString();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
tts.speak(textViewString, TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(textViewString, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
I'd suggest you can take this by using AsyncTask.
An AsyncTask works as follows:
private ProgressDialog pDialog; // Progress Dialog to load during the AsyncTask
private class InitializeSpeechEngine extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(Void aVoid){
// Initialization code goes inside onPreExecute
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("Loading Speech to Text Engine");
pDialog.setMessage("Please Wait...");
pDialog.setCancellable(false);
pDialog.show();
}
#Override
protected void doInBackground(Void... params){
// Perform the speech to text initialization here
}
#Override
protected void onPostExecute(Void aVoid){
// Display Toast that the engine is ready for use.
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Speech to text engine initialization complete", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Void... params){
}
You can start executing the AsyncTask by making the following call.
new InitialiazeSpeechEngine().execute();

I need to generate and display a random number in SystemClock.sleep() with no range

I'm a student at a community college. The following is the Main Activity in which I was tasked to generate a random number instead of the 5 milliseconds to run the sleep()method. I then have to display that random number. I figured out how to accomplish it for the first button, but I keep running into snags for the next two(converting to int, converting to a string for resultsTextView.setText();. I have tried several times to code a method, but then I'm running into other errors because onCreate is void.
package com.example.dan.hour5application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button uiThreadButton;
Button postButton;
Button asyncTaskButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);
resultsTextView = (TextView) findViewById(R.id.textView);
uiThreadButton = (Button) findViewById(R.id.uiThreadButton);
uiThreadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////Achieved a random number here////
Random random = new Random();
int x = random.nextInt(10);
SystemClock.sleep(x);
String aString = Integer.toString(x);
resultsTextView.setText(aString);
}
});
postButton = (Button) findViewById(R.id.post);
postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
resultsTextView.post(new Runnable() {
#Override
public void run() {
resultsTextView.setText("Updated");
}
});
}
}).start();
}
});
asyncTaskButton = (Button) findViewById(R.id.asynctask);
class DelayTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
resultsTextView.setText("Starting AsyncTask");
}
#Override
protected void onPostExecute(Integer result) {
if (result == 0) {
resultsTextView.setText("Updated via AsyncTask");
}
}
#Override
protected Integer doInBackground(Integer... params) {
SystemClock.sleep(5000);
return 0;
}
}
}
}
I have looked at several other examples on Stack, but they aren't quite what I'm doing. I'm only starting my 4th month in Android Development, and I'm still trying to learn Java. The assignment is long gone, and my instructor didn't provide me with help when I asked. Thanks for your help!

Categories