Subject: android : moving the location of an Image View using java code Mon Jun 18, 2018 10:52 am
imageView1.setY(imageView1.getY() + 200);
_________________ MB over and out
Last edited by Moti Barski on Wed Oct 10, 2018 1:43 am; edited 1 time in total
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android SQlite walkthrough Wed Jun 20, 2018 7:00 pm
The database created is saved in a directory: data/data/APP_Name/databases/DATABASE_NAME.
data table : (String name, String pass) this are to example fields you can see them in the inner class : myDbHelper in myDbAdapter class replace and add fields on them to customize your SQDB
helper = new myDbAdapter(this); } public void addUser(View view) { String t1 = Name.getText().toString(); String t2 = Pass.getText().toString(); if(t1.isEmpty() || t2.isEmpty()) { Message.message(getApplicationContext(),"Enter Both Name and Password"); } else { long id = helper.insertData(t1,t2,"hadouken@upgrade.test"); if(id<=0) { Message.message(getApplicationContext(),"Insertion Unsuccessful"); Name.setText(""); Pass.setText(""); } else { Message.message(getApplicationContext(),"Insertion Successful"); Name.setText(""); Pass.setText(""); } } }
public void viewdata(View view) { Message.message(this,helper.getRow(updateold.getText().toString())); /*alternative code to view * all data * stored in the SQliteDb * */ // String data = helper.getData(); // Message.message(this,data); }
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { Message.message(context,"OnUpgrade"); if (oldVersion < 2) { db.execSQL(DATABASE_ALTER_DB); }
key notes : 1 private static final int DATABASE_Version = 2; // was 1 in previous ver private static final String eMail= "eMail"; // Column 4 was added 2 add : if (oldVersion < 2) { db.execSQL(DATABASE_ALTER_DB); } if (oldVersion < 3) { db.execSQL(DATABASE_ALTER_DB2); } add so on to run all upgrades successfully one by one.
getData() will return all data in the db use it to see the changes between the data in prev SQDb version to the new one, in ver 1 the email fields (didn't exist)
public long insertData(String name, String pass, String email) was therefore, also modified : contentValues.put(myDbHelper.eMail, email); was added
_________________ MB over and out
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android enable and send SMS Thu Jun 28, 2018 2:58 pm
android enable and send SMS :
manifest : add : <uses-permission android:name="android.permission.SEND_SMS" /> so it looks like :
main java notice in the oncreate the app checks if SMS permission was enabled if not a dialog pops up asking the user to permit SMS sending for this app, next times the permission isn't needed (it stays permitted):
new AlertDialog.Builder(this) .setTitle("Permission needed") .setMessage("This permission is needed because the app needs to be able to send SMSes") .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE); } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create().show();
} else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
public class MainActivity extends AppCompatActivity { /* * make sure you add : * <uses-permission android:name="android.permission.CALL_PHONE" /> * to AndroidManifest.xml * ___ /___\ (|0 0|) __/{\U/}\_ ___/vvv / \ {~} / _|_P| | /\ ~ /_/ || |_| (____) || \_]/______\ /\_||_/\ _\_||_/_ |] _||_ [| call (_,_||_,_) \/ [] \/ * */ private Button button; private static final int REQUEST_PHONE_CALL = 1;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // ensure enablement of phone calls if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
new AlertDialog.Builder(this) .setTitle("Permission needed") .setMessage("This permission is needed to make phone calls") .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PHONE_CALL); } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create().show();
} else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PHONE_CALL);
import java.util.ArrayList; import android.annotation.TargetApi; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import static android.Manifest.permission.READ_CONTACTS; public class MainActivity extends Activity { private static final int REQUEST_READ_CONTACTS = 444; private ListView mListView; private ProgressDialog pDialog; private Handler updateBarHandler; ArrayList<String> contactList; Cursor cursor; int counter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Reading contacts..."); pDialog.setCancelable(false); pDialog.show(); mListView = (ListView) findViewById(R.id.list); updateBarHandler = new Handler(); // Since reading contacts takes more time, let's run it on a separate thread. new Thread(new Runnable() { @Override public void run() { getContacts(); } }).start(); // Set onclicklistener to the list item. mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //TODO Do whatever you want with the list data Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show(); } }); } private boolean mayRequestContacts() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { return true; } if (shouldShowRequestPermissionRationale(READ_CONTACTS)) { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } else { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } return false; } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getContacts(); } } } public void getContacts() { if (!mayRequestContacts()) { return; } contactList = new ArrayList<String>(); String phoneNumber = null; String email = null; Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI; String _ID = ContactsContract.Contacts._ID; String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME; String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER; Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID; String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER; Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI; String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID; String DATA = ContactsContract.CommonDataKinds.Email.DATA; StringBuffer output; ContentResolver contentResolver = getContentResolver(); cursor = contentResolver.query(CONTENT_URI, null, null, null, null); // Iterate every contact in the phone if (cursor.getCount() > 0) { counter = 0; while (cursor.moveToNext()) { output = new StringBuffer(); // Update the progress message updateBarHandler.post(new Runnable() { public void run() { pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount()); } }); String contact_id = cursor.getString(cursor.getColumnIndex(_ID)); String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME)); int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER))); if (hasPhoneNumber > 0) { output.append("\n First Name:" + name); //This is to read multiple phone numbers associated with the same contact Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null); while (phoneCursor.moveToNext()) { phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER)); output.append("\n Phone number:" + phoneNumber); } phoneCursor.close(); // Read every email id associated with the contact Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null); while (emailCursor.moveToNext()) { email = emailCursor.getString(emailCursor.getColumnIndex(DATA)); output.append("\n Email:" + email); } emailCursor.close(); String columns[] = { ContactsContract.CommonDataKinds.Event.START_DATE, ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.MIMETYPE, }; String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY + " and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME; Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder); Log.d("BDAY", birthdayCur.getCount()+""); if (birthdayCur.getCount() > 0) { while (birthdayCur.moveToNext()) { String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)); output.append("Birthday :" + birthday); Log.d("BDAY", birthday); } } birthdayCur.close(); } // Add the contact to the ArrayList contactList.add(output.toString()); } // ListView has to be updated using a ui thread runOnUiThread(new Runnable() { @Override public void run() { ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_list_item_1, R.id.text1, contactList); mListView.setAdapter(adapter); } }); // Dismiss the progressbar after 500 millisecondds updateBarHandler.postDelayed(new Runnable() { @Override public void run() { pDialog.cancel(); } }, 500); } } }
keynotes : you can get the actual data from the variable output = new StringBuffer(); for example store it into a dictionary key = name, value = rest of the data.
or from the var : ArrayList<String> contactList; using a regex to get the string part you want per contact
2nd keynote : the main java contains code for using a thread to run code in parallal (on an additional cpu core) which speeds up the app.
_________________ MB over and out
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android xml main attributes mini grimoire Wed Jul 04, 2018 10:56 am
text attributes : android:textAlignment="center" android:hint="enter Item" android:textAllCaps="false" allow caps chars android:layout_centerHorizontal="true" center the item on the UserInterface
android:layout_centerHorizontal="true" android:layout_centerVertical="true" full center iten on UI
//get a reference to the button element listed in the XML layout Button speakButton = (Button)findViewById(R.id.speak); //listen for clicks speakButton.setOnClickListener(this);
//check for TTS data Intent checkTTSIntent = new Intent(); checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE); }
//respond to button clicks public void onClick(View v) {
//get the text entered EditText enteredText = (EditText)findViewById(R.id.enter); String words = enteredText.getText().toString(); speakWords(words); }
//speak the user text private void speakWords(String speech) {
//act on result of TTS data check protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) { if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { //the user has the necessary data - create the TTS myTTS = new TextToSpeech(this, this); } else { //no data - install it now Intent installTTSIntent = new Intent(); installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(installTTSIntent); } } }
//setup TTS public void onInit(int initStatus) {
//check for successful instantiation if (initStatus == TextToSpeech.SUCCESS) { if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE) myTTS.setLanguage(Locale.US); } else if (initStatus == TextToSpeech.ERROR) { Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show(); } } }
hadouken
_________________ MB over and out
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android studio progress dialogs walkthrough Mon Jul 09, 2018 12:53 am
private void askPermission() { //create a list of permissions List<String> listPerm = new ArrayList<>(); // contains the recog results per talk //get permission status for audio record int audioPerm = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO); //check if the record audio permission is granted if (audioPerm != PackageManager.PERMISSION_GRANTED) { listPerm.add(Manifest.permission.RECORD_AUDIO); } else { hasAudioPermission = true; }
//check if our list is not empty, and ask permission for it's items. if (!listPerm.isEmpty()) { //ask permission by requests. ActivityCompat.requestPermissions(this, listPerm.toArray(new String[listPerm.size()]), REQUEST_CODE); }
}
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults.length > 0) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { //we can do what ever we like. hasAudioPermission = true; } else { //tell the user that we can't work, becuase we don't have a permission Toast.makeText(context, getResources().getString(R.string.permission_denied), Toast.LENGTH_SHORT).show(); } } }
private void runSpeechRecognition() { //handle the speech recognition intent Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); //tell the intent that we want to speak freely intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); //tell the intent that we want to use the default language intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault()); //show the user a text to explain what we want. intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getResources().getString(R.string.recIntent)); if (hasAudioPermission) { try { startActivityForResult(intent, RECOGNITION_RESULT); } catch (ActivityNotFoundException e) { Log.e("err", "runSpeechRecognition: " + e.getMessage()); Toast.makeText(context, "ERROR", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.e("WTF", "runSpeechRecognition: " + e.getMessage()); } } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { //in case the request code is 2 - recognition intent case RECOGNITION_RESULT: if (resultCode == RESULT_OK && data != null) { //get array list of all our result (can be 1, can be 5) ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); LangAdapter myAdapter = new LangAdapter(context,result); lstRes.setAdapter(myAdapter); } break;
default: Toast.makeText(context, "the programmer is not so bright", Toast.LENGTH_SHORT).show(); } } }
key note : access the result : String x = result.get(0).trim().toLowerCase().substring(1,result.get(0).trim().length()) + ""; place it in : onActivityResult in switch (requestCode) in if (resultCode == RESULT_OK && data != null) { (line 131)
_________________ MB over and out
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android special toast Sat Jul 14, 2018 1:59 am
Add dependency in your app module dependencies { implementation 'com.sdsmdg.tastytoast:tastytoast:0.1.1' }
Usage Java TastyToast.makeText(getApplicationContext(), "Hello World !", TastyToast.LENGTH_LONG, TastyToast.WARNING);
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TastyToast.makeText(getApplicationContext(), "Hello World !", TastyToast.LENGTH_LONG, TastyToast.SUCCESS); // type TastyToast. at TastyToast.SUCCESS to see more options } }
special toast
_________________ MB over and out
Last edited by Moti Barski on Tue Jul 24, 2018 6:22 pm; edited 1 time in total
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android xml and json from url parse Sun Jul 15, 2018 6:20 pm
@SuppressLint("StaticFieldLeak") public void getDataXML() { //we never use void in AsyncTask, we need to use Void new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { //we need to open HTTP URL Connection to our desired URL (www.boi.org.il) HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(XML_URL).openConnection(); BufferedReader buf = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = buf.readLine()) != null) { xmlString += line; } } catch (IOException e) { e.printStackTrace(); } finally { connection.disconnect(); }
private void parseXML(String xmlString) { //we will create a document builder that will allow us an easier access to our XML String DocumentBuilder builder; try { Log.e("XML", "onPostExecute: " + xmlString); builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document DOM = builder.parse(new InputSource(new StringReader(xmlString)));
//let got on our entire collection to get the data for (int counter = 0; counter < itemName.getLength(); counter += 1) { myCurList.add(new ClsCur( itemName.item(counter).getTextContent(), Integer.parseInt(itemUnit.item(counter).getTextContent()), itemCur.item(counter).getTextContent(), itemCountry.item(counter).getTextContent(), Float.parseFloat(itemRate.item(counter).getTextContent()), Float.parseFloat(itemChange.item(counter).getTextContent()) )); } Adapter_Cur myAdapter = new Adapter_Cur(context, myCurList); lstCur.setAdapter(myAdapter); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); }
}
@SuppressLint("StaticFieldLeak") public void getDataJSON() { //we never use void in AsyncTask, we need to use Void new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { //we need to open HTTP URL Connection to our desired URL (www.boi.org.il) HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(JSON_URL).openConnection(); BufferedReader buf = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = buf.readLine()) != null) { jsonString += line; } } catch (IOException e) { e.printStackTrace(); } finally { connection.disconnect(); }
private void parseJson(String jsonString) { //declaring the json object and passing the string to it. try { //get the entire string and treat it as a JSON object JSONObject jsonObject = new JSONObject(jsonString); //get the currently object JSONObject currently = jsonObject.getJSONObject("currently"); Log.e("currently", "parseJson: "+currently ); //get the summry which is a string. String summary = currently.getString("summary"); //get the temp. Double temp = currently.getDouble("temperature"); // f->c int tempC=(int)(((temp-32)*(5/9.0))*100)/100; int hum=(int)(currently.getDouble("humidity")*100); String display = "summary:"+summary+" tempC:"+tempC+"Cel. humidity:"+hum+"%"; Log.e("JSON", "parseJson: "+display ); } catch (JSONException e) { e.printStackTrace(); } } }
Last edited by Moti Barski on Mon Jul 23, 2018 3:44 pm; edited 3 times in total
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: cardview on recycler view Sat Jul 21, 2018 9:45 am
add : implementation 'com.android.support:recyclerview-v7:27.1.1' implementation 'com.android.support:cardview-v7:27.1.1' to gradle module so it looks like :
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
//set title for our tag private final String TAG="RecyclerView Adapter"; //our data set list private List<DataObject>lstDataSet; //create interface for click listener public interface MyClickListener{ void onItemClick(int position, View v); } //our click listener that will be sent by method (interface) private MyClickListener myClickListener;
//our c'tor to our class :) public MyRecyclerViewAdapter(List<DataObject> lstDataSet) { this.lstDataSet = lstDataSet; }
public class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView victimName; TextView victimSlogan; Button btnDel; //c'tor for our internal class which work as: //1. set pointer //2. set on click listener to our entire item. public DataObjectHolder(View itemView) { super(itemView); victimName=itemView.findViewById(R.id.txtName); victimSlogan=itemView.findViewById(R.id.txtSlogan); btnDel=itemView.findViewById(R.id.btnMoti); itemView.setOnClickListener(this); }
//because we declare interface as implementation of on click listener, we can add some extra //information to our onclick. //since we using the method getAdapterPosition(), which give us the index of the position //now we hold the position and the view, instead of holding only the view without the position @Override public void onClick(View v) { myClickListener.onItemClick(getAdapterPosition(),v); } }
//using the interface we set on click listener but for single item public void setOnItemClickListener(MyClickListener myClickListener) { this.myClickListener=myClickListener; }
//create a view holder, which will be created upon using it @NonNull @Override public DataObjectHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { //inflate our card view row layout View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false); //set the inflated view to our holder DataObjectHolder dataObjectHolder = new DataObjectHolder(view); //return the data object holder return dataObjectHolder; }
@Override public void onBindViewHolder(@NonNull DataObjectHolder holder, final int position) { //set the label (our header which show index : XX) holder.victimName.setText(lstDataSet.get(position).getmText1()); //set the slogan holder.victimSlogan.setText(lstDataSet.get(position).getmText2()); //set delete button inside the card view holder.btnDel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { lstDataSet.remove(position); notifyItemRemoved(position); } }); Log.e(TAG, "onBindViewHolder: "+lstDataSet.get(position).getmText1()); }
@Override public int getItemCount() { return lstDataSet.size(); }
//CRUD public void addItem(DataObject dataObject, int index) { lstDataSet.add(index,dataObject); notifyItemInserted(index); }
public void deleteItem(int index) { lstDataSet.remove(index); notifyItemRemoved(index); }
public class MainActivity extends AppCompatActivity { private String[] victimName={"Zeev","Amital","Nipo","Buf","Sami","Eitan"}; private String[] victimSlogan={"hadoken","I from Chabad","I want to see asuka kazama ","Where is Alex Tazi","Move your car","Tell me when you land"};
//create a recycler view object private RecyclerView myRecyclerView; //create an (inner class) adapter for the recycler view private RecyclerView.Adapter myAdapter; //create a recycler view layout manager private RecyclerView.LayoutManager myLayoutManager;
public class MainActivity extends AppCompatActivity {
private int groupID= Menu.FIRST; private final int TEXT_ID = Menu.FIRST; private final int IMAGE_ID = Menu.FIRST+1; private final int VIDEO_ID = Menu.FIRST+2;
to : <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
to remove action bar from a certain activity in AndroidManifest.xml :
change : per activity : <activity android:name=".SignUpActivity" android:theme="@style/AppTheme.NoActionBar"/>
In your AndroidManifest.xml use NoActionBar theme for your Activity like this: <activity android:name=".SignUpActivity" android:theme="@style/AppTheme.NoActionBar"/>
and in your styles.xml <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style>
public class Motti { Intent shareIntent; Context context; String myType;
public Motti(Context context, String mimeType) { this.context=context; this.myType=mimeType; }
public void startChooser() { //intent for sending action (like send image,audio,video,etc...) shareIntent = new Intent(Intent.ACTION_SEND); //set mime type shareIntent.setType(myType+"/*"); //tell the user what you want to do.... shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Moti want's to share"); //what i want to share (for example a text) shareIntent.putExtra(Intent.EXTRA_TEXT,"Hello from motti :)"); //set a package http://shareIntent.setPackage("com.whatsapp"); //start activity :) context.startActivity(Intent.createChooser(shareIntent,"Send moti with:")); } }
using the class : Motti x = new Motti(this.getApplicationContext(),"text"); x.startChooser();
_________________ MB over and out
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android splash screen stand alone ver walkthrough Wed Jul 25, 2018 5:36 pm
keynote : in manifest took <category android:name="android.intent.category.LAUNCHER" /> from main activity and put it in <activity android:name=".SplashScreen">
_________________ MB over and out
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android vibrator service Thu Jul 26, 2018 1:22 am
public class MainActivity extends AppCompatActivity { Button btnWifi; ListView lstView; Context context; final int ACCESS_FINE_LOCATION =1; final int ACCESS_COARSE_LOCATION =1; WifiManager wifi; //a manger for all our wifi requests
private void getWifiPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this) .setTitle("gps Permission needed to scan available wifi") .setMessage("This permission is needed because the app needs to be able to scan wifi") .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION); } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create().show();
} else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);
}
}
private void scanWifi() { //wifi example -> pointer to system service WIFI wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled()) { getWifiList(); } }
private void getWifiList() { List<ScanResult> wifiList = wifi.getScanResults(); List<String> foundSSID = new ArrayList<>(); for (ScanResult item:wifiList) { foundSSID.add(item.SSID); } WifiAdapter myAdapter = new WifiAdapter(context,foundSSID); lstView.setAdapter(myAdapter); }
}
4 wifi scan walkthrough look up
_________________ MB over and out
Last edited by Moti Barski on Fri Jul 27, 2018 7:25 am; edited 1 time in total
Moti Barski super
Posts : 476 Join date : 2011-08-02
Subject: android custom service Thu Jul 26, 2018 2:22 am
add : <service android:name=".MyCustomService"/> to the manifest above application so it looks like :
public class MyCustomService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; }
@Override public int onStartCommand(Intent intent, int flags, int startId) { MainActivity.lnrLoading.setVisibility(View.VISIBLE); return super.onStartCommand(intent, flags, startId); }
@Override public void onDestroy() { MainActivity.lnrLoading.setVisibility(View.INVISIBLE); super.onDestroy(); } }
private void setPointer() { myService = new Intent(this,MyCustomService.class); btnStart=findViewById(R.id.btnStart); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isMyServiceRunning(MyCustomService.class)) {
startService(myService); } } });
btnStop=findViewById(R.id.btnStop); btnStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isMyServiceRunning(MyCustomService.class)) { stopService(myService); } } }); lnrLoading=findViewById(R.id.lnrLoading); }
private boolean isMyServiceRunning(Class<?> serviceClass) { //create activity manager to get all process that are running in the system ActivityManager manger = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); //go on entire collection and check if there is a matching name to the serviceClass name //that we gave in the args. for (ActivityManager.RunningServiceInfo service:manger.getRunningServices(Integer.MAX_VALUE)) { //if we found, return true if (serviceClass.getName().equals(service.service.getClassName())) { Log.e("onStop", "onClick: start" ); return true; } } //if we didn't found , return false as a default return false; }
}
keynote : notice in main activity the code snippet :
Code:
private boolean isMyServiceRunning(Class<?> serviceClass) { //create activity manager to get all process that are running in the system ActivityManager manger = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); //go on entire collection and check if there is a matching name to the serviceClass name //that we gave in the args. for (ActivityManager.RunningServiceInfo service:manger.getRunningServices(Integer.MAX_VALUE)) { //if we found, return true if (serviceClass.getName().equals(service.service.getClassName())) { Log.e("onStop", "onClick: start" ); return true; } } //if we didn't found , return false as a default return false; }