I used this library: https://github.com/johannilsson/android-pulltorefresh
works well, but in a ListView simple (simple is what I say in the pattern of cell android).
I wore a Adpter put in my custom ListView to cells with image, title and description.
my class with adpter:
public class extends Main_podcast ListActivity implements {OnItemClickListener
private Bitmap pathImgSmal;
/ ** Called When the activity is first created. * /
# Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
Mybundle bundle = new Bundle ();
mybundle.putString ("podcastnumber", "0");
/ / Check for connection and starts downloading the XML
Connected conected Boolean = (this);
if (conected == true) {
DoInBackground new (). execute ();
Else {}
new AlertDialog.Builder (Main_podcast.this)
. SetTitle ("Alert!")
. SetMessage ("Unable to connect to the Internet," +
"Check your network or try again later.")
. SetNeutralButton ("OK"
new DialogInterface.OnClickListener () {
public void onClick (DialogInterface dialog,
int which) {}
}). Show ();
}
}
/ / Method calls the XML Parser
public void do_update ()
{
PodcastParser.parse ();
}
/ / Method that populates the list view with XML parameters
public void populate_listview ()
{
List <Itens> podcastList <Itens> = new ArrayList ();
for (int i = 0; i <arraysPodcast.PodcastTitle.length; i + +) {
end item Items = new Items ();
item.setTitle (arraysPodcast.PodcastTitle [i]);
item.setData (arraysPodcast.PodcastData [i]);
item.setImage (arraysPodcast.ArrayIMGPodcast [i]);
podcastList.add (item);
}
setListAdapter (new PodcastAdapter (this, podcastList));
ListView shot getListView = ();
shot.setOnItemClickListener ((OnItemClickListener) this);
}
public void onItemClick (AdapterView <?> arg0, View v, int position, long id) {
/ / Start the Activity podcast regarding your number from the list
Myintent intent = new Intent ("com.example.player.PODCAST");
Mybundle bundle = new Bundle ();
mybundle.putInt ("podcastnumber" position);
myintent.putExtras (mybundle);
startActivity (myintent);
}
private class extends DoInBackground AsyncTask <Void, Void, Void>
implements DialogInterface.OnCancelListener
{
ProgressDialog private dialog;
protected void OnPreExecute ()
{
dialog = ProgressDialog.show (Main_podcast.this, "", "Loading Podcasts ...", true);
}
protected void doInBackground (Void. unused ..)
{
do_update ();
return null;
}
OnPostExecute protected void (Void unused)
{
dialog.dismiss ();
populate_listview ();
}
public void onCancel (DialogInterface dialog)
{
cancel (true);
dialog.dismiss ();
}
}
public static boolean Connected (Context context) {
try {
= ConnectivityManager cm (ConnectivityManager)
context.getSystemService (Context.CONNECTIVITY_SERVICE);
LogSync String = null;
LogToUserTitle String = null;
if (cm.getNetworkInfo (ConnectivityManager.TYPE_MOBILE). isConnected ()) {
LogSync + = "\ nConectado 3G Internet";
LogToUserTitle + = "Connected to 3G Internet";
return true;
} Else if (cm.getNetworkInfo (ConnectivityManager.TYPE_WIFI). IsConnected ()) {
LogSync + = "\ nConectado WIFI Internet";
LogToUserTitle + = "Connected to Wireless Internet";
return true;
Else {}
LogSync + = "\ nYou have internet connection";
LogToUserTitle + = "Do not have an internet connection";
return false;
}
} Catch (Exception e) {
return false;
}
}
} / / Class
the question is, how do I implement my class with a custom cell library johannilsson?
any help is welcome!
decided as follows:
public class PullToRefreshActivity extends ListActivity implements OnItemClickListener {
private LinkedList<String> mListItems;
private List<Itens> podcastList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pull_to_refresh);
// Set a listener to be invoked when the list should be refreshed.
// ======================================================
Bundle mybundle = new Bundle();
mybundle.putString("podcastnumber", "0");
//verifica se há conexao e inicia download do XML
Boolean conected = Conectado(this);
if(conected == true){
new DoInBackground().execute();
}else{
new AlertDialog.Builder(PullToRefreshActivity.this)
.setTitle("Alerta!")
.setMessage("Não foi possível estabelecer uma conexão com a Internet," +
"verifique sua rede ou tente novamente mais tarde.")
.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {}
}).show();
}
// ======================================================
((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new DoInBackground().execute();
}
});
}
// ==================================================================
public void do_update()
{
PodcastParser.parse();
}
//metodo que preenche a list view com parametros do XML
public void populate_listview()
{
podcastList = new ArrayList<Itens>();
for (int i = 0; i < arraysPodcast.PodcastTitle.length; i++) {
final Itens item = new Itens();
item.setTitle(arraysPodcast.PodcastTitle[i]);
item.setData(arraysPodcast.PodcastData[i]);
item.setImage(arraysPodcast.ArrayIMGPodcast[i]);
podcastList.add(item);
}
setListAdapter(new PodcastAdapter(this, podcastList));
((PullToRefreshListView) getListView()).setOnItemClickListener((OnItemClickListener) this);
}
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
//Inicia Activity da podcast referente a seu numero da lista
Intent myintent = new Intent("com.example.player.PODCAST");
Bundle mybundle = new Bundle();
mybundle.putInt("podcastnumber", (position-1));
Log.e("posicao na lista",""+position);
myintent.putExtras(mybundle);
startActivity(myintent);
}
private class DoInBackground extends AsyncTask<Void, Void, Void>
implements DialogInterface.OnCancelListener
{
private ProgressDialog dialog;
protected void onPreExecute()
{
dialog = ProgressDialog.show(PullToRefreshActivity.this, "", "Carregando Podcasts...", true);
}
protected Void doInBackground(Void... unused)
{
PodcastAdapter.topBar=true;
do_update();
return null;
}
protected void onPostExecute(Void unused)
{
((PullToRefreshListView) getListView()).onRefreshComplete();
dialog.dismiss();
populate_listview();
}
public void onCancel(DialogInterface dialog)
{
cancel(true);
dialog.dismiss();
}
}
public static boolean Conectado(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
String LogSync = null;
String LogToUserTitle = null;
if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()) {
LogSync += "\nConectado a Internet 3G ";
LogToUserTitle += "Conectado a Internet 3G ";
return true;
} else if(cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()){
LogSync += "\nConectado a Internet WIFI ";
LogToUserTitle += "Conectado a Internet WIFI ";
return true;
} else {
LogSync += "\nNão possui conexão com a internet ";
LogToUserTitle += "Não possui conexão com a internet ";
return false;
}
} catch (Exception e) {
return false;
}
}
}
Related
Problem is in the Fragment which consume the USB service and cannot register the service returning when debugging always null.
I have USB Service which is working totally fine in Activity, then I changed the code to work in fragment so i can use ViewPager ..
Now the problem that USB service is always return null and I have applied same code but it seems fragment needs other work than Activity which i still didn't catch and here's.
here's the fragment code after adding the service class and mention it in manifest.
public class RealTimeFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
TextView tvTimeStamp, tvPm25, tvPm10, tvTemp, tvHumid, tvCo2, tvTvoc, tvNoise, tvPa;
RoundCornerProgressBar pbPm25, pbPm10, pbTemp, pbHumid, pbCo2, pbTvoc, pbNoise, pbPa;
ImageView ivVent ;
public static final String TAG = "MainActivity";
private UsbService usbService;
private RealTimeFragment.MyHandler mHandler;
static String myJson = "";
static int dbCount = 0;
static ControlViewModel controlViewModel;
static View mView;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
usbService.changeBaudRate(9600);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action!=null) {
switch (action) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
}
};
public RealTimeFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static RealTimeFragment newInstance(int sectionNumber) {
RealTimeFragment fragment = new RealTimeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.realtime_layout_fragment, container, false);
tvTimeStamp = rootView.findViewById(R.id.tv_serial_output);
tvPm25 = rootView.findViewById(R.id.tv_pm25);
pbPm25 = rootView.findViewById(R.id.pb_pm25);
tvPm10 = rootView.findViewById(R.id.tv_pm10);
pbPm10 = rootView.findViewById(R.id.pb_pm10);
tvTemp = rootView.findViewById(R.id.tv_temp);
pbTemp = rootView.findViewById(R.id.pb_temp);
tvHumid = rootView.findViewById(R.id.tv_humid);
pbHumid = rootView.findViewById(R.id.pb_humid);
tvCo2 = rootView.findViewById(R.id.tv_co2);
pbCo2 = rootView.findViewById(R.id.pb_co2);
tvTvoc = rootView.findViewById(R.id.tv_tvoc);
pbTvoc = rootView.findViewById(R.id.pb_tvoc);
tvNoise = rootView.findViewById(R.id.tv_noise);
pbNoise = rootView.findViewById(R.id.pb_noise);
tvPa = rootView.findViewById(R.id.tv_pressure);
pbPa = rootView.findViewById(R.id.pb_pressure);
ivVent = rootView.findViewById(R.id.iv_vent);
mHandler = new RealTimeFragment.MyHandler(getActivity());
//assert getArguments() != null;
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
this.mView = rootView;
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
return rootView;
}
#Override
public void onResume() {
super.onResume();
// setFilters(); // Start listening notifications from UsbService
// startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
super.onPause();
usbService.unregisterReceiver(mUsbReceiver);
usbService.unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(getContext(), service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
usbService.startService(startService);
}
Intent bindingIntent = new Intent(getContext(), service);
usbService.bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
Log.e("startService",mUsbReceiver.toString());
usbService.registerReceiver(mUsbReceiver, filter);
// LocalBroadcastManager.getInstance(usbService).registerReceiver(mUsbReceiver, filter);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<Activity> mActivity;
private MyHandler(Activity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String buffer = (String) msg.obj;
myJson += buffer;
if (buffer.indexOf('}') >= 0) {
try {
Data responseBegin = new Gson().fromJson(myJson, Data.class);
SystemControl systemControl = new SystemControl(responseBegin.getStaticFilter() == 1 ? true:false, responseBegin.getAutoVent() == 1 ? true:false, responseBegin.getFanSpeed());
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
controlViewModel.getSystemControl().postValue(systemControl);
updateUI(responseBegin);
myJson = "";
} catch (Exception e) {
myJson = "";
}
}
break;
case UsbService.CTS_CHANGE:
Toast.makeText(mActivity.get(), "CTS_CHANGE", Toast.LENGTH_LONG).show();
break;
case UsbService.DSR_CHANGE:
Toast.makeText(mActivity.get(), "DSR_CHANGE", Toast.LENGTH_LONG).show();
break;
case UsbService.SYNC_READ:
String buffer2 = (String) msg.obj;
myJson += buffer2;
if (buffer2.indexOf('}') >= 0) {
try {
Data responseBegin = new Gson().fromJson(myJson, Data.class);
SystemControl systemControl = new SystemControl(responseBegin.getStaticFilter() == 1 ? true:false, responseBegin.getAutoVent() == 1 ? true:false, responseBegin.getFanSpeed());
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer. controlViewModel.getSystemControl().postValue(systemControl);
updateUI(responseBegin);
myJson = "";
} catch (Exception e) {
myJson = "";
}
}
break;
}
}
}
}
This is because you're calling:
usbService.registerReceiver(mUsbReceiver, filter);
before starting the service, which you have done in the following line:
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
return rootView;
}
So, you just need to flip the code to solve the problem:
startService(UsbService.class, usbConnection, null);
setFilters();
My app has an itinerary function, the part where you create a new itinerary involves selecting from 2 spinners which drop down to present different options. The data coming from MQsql database and the JSON response is correct for both sets. Currently i have been able to get either one set of the data to load in the correct spinner (being which either just transport info or attraction info but not both), or i have been able to get both sets of data to load but both are displayed in the same 2 spinners. I need them to be separated into there allocated spinners but need help doing this as i dont undertand what im doing wrong.
createItinerary class:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
LayoutInflater myInflator;
View myView;
DBManager db;
myAdapter adapter;
String NAME;
String LOCATION;
String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
TextView TextTime;
String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
new GetTransport().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, 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.go_home){
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all food categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
/*
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Entities.remove(position);
finalEntities.remove(position);
loadAttractions();
}
});*/
return myView;
}
}
}
Thank you to anyone who can help me with this.
firstly, i read all answers related with this problem but i didn't solve this error. My program is running but very laggy and slow. i tryed use smaller images and use async task but my problem is continued. here is my code
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
NotificationManager manager;
public Veri veri,veri1;
int x= 0;
private Timer autoUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
veri1 = new Veri();
x=veri1.getList().size();
recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
onResume();
new AsyncCaller().execute();
}
#Override
protected void onStart() {
super.onStart();
}
////////////////////////////////////////////
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
updateHTML();
}
});
}
}, 0, 60000);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
////////////////////////////////////
private void updateHTML(){
// your logic here
RecyclerAdapter adapter=new RecyclerAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
veri = new Veri();
int a = veri.getList().size();
if(a!=x){
generateNotification(MainActivity.this,"Listede Degisim Var");
}
x=a;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
// search action
case R.id.action_location_found:
// location found
LocationFound();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void LocationFound() {
Intent i = new Intent(MainActivity.this, LocationFound.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
private void generateNotification(Context context,String message){
int notificationId = 001;
Intent viewIntent = new Intent(context, MainActivity.class);
PendingIntent viewPendingIntent =
PendingIntent.getActivity(context, 0, viewIntent, 0);
NotificationCompat.Builder notificationBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.dikat)
.setContentTitle("Bildirim")
.setContentText(message)
.setContentIntent(viewPendingIntent)
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.bildirim))
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(context);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
here is my data class
public class Veri extends ActionBarActivity {
NotificationManager manager;
Notification myNotication;
String ip, db, un, passwords;
Connection connect,conn;
PreparedStatement stmt;
ResultSet rs;
TextView tv;
int position1=0;
Button b1;
ArrayList<String> data = new ArrayList<String>();
ArrayList<String> data2 = new ArrayList<String>();
public Veri(){
ip = "x.x.x.x";
un = "x";
passwords = "x";
db = "xxx";
connect = CONN(un, passwords, db, ip);
String query = "SELECT Adsoyad,(DATEPART(hour, BeklemeSuresi) * 3600) + (DATEPART(minute, BeklemeSuresi) * 60) + DATEPART(second, BeklemeSuresi) as SecondsFromMidnight,Durum FROM [dbo].[IslemiDevamEdenHasta] (1)";
try {
// connect = CONN(un, passwords, db, ip);
stmt = connect.prepareStatement(query);
rs = stmt.executeQuery();
while (rs.next()) {
int b = (int)rs.getInt("SecondsFromMidnight")/60;
if(b>50) {
String id = rs.getString("Adsoyad");
String id2 = rs.getString("Durum");
String full = id + " " + id2;
String a = "" + b;
data.add(full);
data2.add(a);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<String> getList() {
return data;
}
public ArrayList<String> getList2() {
return data2;
}
#SuppressLint("NewApi")
private Connection CONN(String _user, String _pass, String _DB,
String _server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL = "jdbc:jtds:sqlserver://" + _server + ";"
+ "databaseName=" + _DB + ";user=" + _user + ";password="
+ _pass + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
and here is my recycler class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
public Veri veri = new Veri();
int sayi=0;
ArrayList<String> liste = veri.getList();
ArrayList<String> liste2 = veri.getList2();
static ArrayList<String> liste3 = new ArrayList<String>() ;
Context context;
LayoutInflater inflater;
public RecyclerAdapter(Context context) {
this.context=context;
inflater=LayoutInflater.from(context);
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v=inflater.inflate(R.layout.item_list, parent, false);
RecyclerViewHolder viewHolder=new RecyclerViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
liste3.add("a");
sayi = 0;
for (int j = 0; j < liste3.size(); j++) {
if (liste3.get(j).equals(liste.get(position))) {
sayi++;
}
if (sayi == 0) {
holder.tv1.setText(liste.get(position));
holder.tv2.setText(liste2.get(position));
holder.imageView.setOnClickListener(clickListener);
holder.imageView.setTag(holder);
} else {
holder.tv1.setText(liste.get(position));
holder.tv2.setText(liste2.get(position));
holder.imageView.setOnClickListener(clickListener);
holder.imageView.setImageResource(R.drawable.ic_checkin);
}
}
}
View.OnClickListener clickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerViewHolder vholder = (RecyclerViewHolder) v.getTag();
int position = vholder.getPosition();
//Toast.makeText(context,"This is position "+position,Toast.LENGTH_LONG ).show();
vholder.imageView.setImageResource(R.drawable.ic_checkin);
liste3.add(liste.get(position));
}
};
#Override
public int getItemCount() {
return liste.size();
}
}
what is my problem??
you doing so much coding for loading image.There are some third party api so you can refer it. so it may be helpful to load your image easily and memory management control is handle by that api also here just refer this tutorial.
I need help to find out why it wont go to the next activity (case R.id.Signin_Btn), I've got this issue in another Activity which was perfectly working before this class was made.
I've been through and checked everything and cant find a way to resolve this issue.
public class Login extends ActionBarActivity implements View.OnClickListener {
ArrayList<Driver> DriverArrayList;
DriverAdapter Dadapter;
ArrayList<Vehicle> VehicleArrayList;
VehicleAdapter Vadapter;
ArrayList<Plot> PlotArrayList;
PlotAdapter Padapter;
ImageButton Driver_Btn;
ImageButton Vehicle_Btn;
ImageButton Plot_Btn;
Button Signin_Btn;
private Intent myIntent;
private int DriverID = 0;
private int VehicleID = 0;
private int PlotID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Driver_Btn = (ImageButton) findViewById(R.id.Select_Driver);
Driver_Btn.setOnClickListener(this);
Vehicle_Btn = (ImageButton) findViewById(R.id.Select_Vehicle);
Vehicle_Btn.setOnClickListener(this);
Plot_Btn = (ImageButton) findViewById(R.id.Select_Plot);
Plot_Btn.setOnClickListener(this);
Signin_Btn = (Button) findViewById(R.id.Signin_Btn);
Signin_Btn.setOnClickListener(this);
//ArrayList
DriverArrayList = new ArrayList<Driver>();
VehicleArrayList = new ArrayList<Vehicle>();
PlotArrayList = new ArrayList<Plot>();
new JSONAsyncTask().execute("N/A");
ListView DlistView = (ListView) findViewById(R.id.DriverList);
ListView VlistView = (ListView) findViewById(R.id.VehicleList);
ListView PlistView = (ListView) findViewById(R.id.PlotList);
Dadapter = new DriverAdapter(getApplicationContext(), R.layout.driver_row, DriverArrayList);
Vadapter = new VehicleAdapter(getApplicationContext(), R.layout.vehicle_row, VehicleArrayList);
Padapter = new PlotAdapter(getApplicationContext(), R.layout.plot_row, PlotArrayList);
DlistView.setAdapter(Dadapter);
VlistView.setAdapter(Vadapter);
PlistView.setAdapter(Padapter);
Driver_Btn.setBackgroundColor(Color.GREEN);
DlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
DriverID = DriverArrayList.get(position).getID();
ResetButtonColours();
arg1.setSelected(true);
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
VlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
VehicleID = VehicleArrayList.get(position).getID();
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
PlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
PlotID = PlotArrayList.get(position).getID();
}
});
}
private void ResetButtonColours() {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
DriverListView.setVisibility(View.GONE);
VehicleListView.setVisibility(View.GONE);
PlotListView.setVisibility(View.GONE);
Driver_Btn.setBackgroundColor(Color.TRANSPARENT);
Vehicle_Btn.setBackgroundColor(Color.TRANSPARENT);
Plot_Btn.setBackgroundColor(Color.TRANSPARENT);
}
#Override
public void onClick(View v) {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
switch (v.getId()) {
case R.id.Select_Driver:
this.ResetButtonColours();
Driver_Btn.setBackgroundColor(Color.GREEN);
DriverListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Vehicle:
this.ResetButtonColours();
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Plot:
this.ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
break;
case R.id.Signin_Btn:
if (DriverID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Driver!", Toast.LENGTH_LONG).show();
} else if (VehicleID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Vehicle!", Toast.LENGTH_LONG).show();
} else if (PlotID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Plot!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Just a minute!", Toast.LENGTH_LONG).show();
myIntent = new Intent(this, Dashboard.class);
//myIntent.putExtra("key", value); //Optional parameters
startActivity(myIntent);
}
break;
}
}
public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Login.this);
dialog.setMessage("Loading, Please Wait");
dialog.setTitle("Connecting to Server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet HttpPost = new HttpGet(urls[0]);
HttpClient HttpClient = new DefaultHttpClient();
HttpResponse Response = HttpClient.execute(HttpPost);
int Status = Response.getStatusLine().getStatusCode();
//if (Status == 200) {
HttpEntity Entity = Response.getEntity();
String Data = EntityUtils.toString(Entity);
JSONObject Object = new JSONObject(Data);
JSONArray DriverArray = Object.getJSONArray("drivers");
for (int i = 0; i < DriverArray.length(); i++) {
JSONObject Current = DriverArray.getJSONObject(i);
Driver Driver = new Driver();
Driver.setID(Current.getInt("id"));
Driver.setName(Current.getString("name"));
DriverArrayList.add(Driver);
}
JSONArray VehicleArray = Object.getJSONArray("vehicles");
for (int i = 0; i < VehicleArray.length(); i++) {
JSONObject Current = VehicleArray.getJSONObject(i);
Vehicle Vehicle = new Vehicle();
Vehicle.setID(Current.getInt("id"));
Vehicle.setName(Current.getString("make") + ' ' + Current.getString("model"));
Vehicle.setReg("(" + Current.getString("reg") + ")");
VehicleArrayList.add(Vehicle);
}
JSONArray PlotArray = Object.getJSONArray("plots");
for (int i = 0; i < PlotArray.length(); i++) {
JSONObject Current = PlotArray.getJSONObject(i);
Plot Plot = new Plot();
Plot.setID(Current.getInt("id"));
Plot.setName(Current.getString("name"));
PlotArrayList.add(Plot);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
Dadapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to Fetch Content from Server", Toast.LENGTH_LONG).show();
}
}
}
}
Have you added the new Activity to the manifest file?
Add this
<activity
android:name=".Dashboard"
android:label="Dashboard" />
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.