· 7 years ago · Nov 15, 2018, 05:50 PM
1Send string from one intent to another
2
3MainActivity.java
4
5public void sendMessage(View view){
6
7 EditText editText = findViewById(R.id.user_message);
8 String message = editText.getText().toString();
9
10 Intent intent = new Intent(this, MessageActivity.class);
11 intent.putExtra("EXTRA_MESSAGE",message);
12 startActivity(intent);
13}
14
15MessageActivity.java
16
17onCreate(){
18 Intent intent = getIntent();
19
20 String message = intent.getStringExtra("EXTRA_MESSAGE");
21 TextView textView = findViewById(R.id.display_message);
22 textView.setText(message);
23}
24
25
26Text Spinner(Dropbox)
27strings.xml
28
29<string-array name="numbers">
30 <item>One</item>
31 <item>Two</item>
32 <item>Three</item>
33</string-array>
34
35MainActivity.java extends AppCompatActivity implements AdapterView.OnItemSelectedListener
36
37Spinner spinner = findViewById(R.id.spinner1);
38ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.numbers,android.R.layout.simple_spinner_item);
39adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
40spinner.setAdapter(adapter);
41spinner.setOnItemSelectedListener(this);
42
43Add Method
44onItemSelected
45String text = parent.getItemAtPosition(position).toString();
46Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
47
48DatePicker
49Create Button(id:button, text:openDatePicker),TextView(id:textView, text:date)
50
51NewJavaClass DatePickerFragment.java, Superclass:DialogFragment(android.support.v4.app)
52Ctrl+O -> onCreateDialog()
53 Calendar c = Calendar.getInstance();
54 int year = c.get(Calendar.YEAR);
55 int month = c.get(Calendar.MONTH);
56 int day = c.get(Calendar.DAY_OF_MONTH);
57
58 return new DatePickerDialog(getActivity(),(DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
59
60MainActivity.java implements OnDateSetListener
61 Button button = (Button)findViewById(R.id.button);
62 button.setOnClickListener(new View.OnClickListener(){
63 @Override
64 public void onClick(View v){
65 DialogFragment datePicker = new DatePickerFragment();
66 datePicker.show(getSupportFragmentManager(),"date picker");
67 }
68 });
69
70Implement methods onDateSet()
71
72 Calendar c = Calendar.getInstance();
73 c.set(Calendar.YEAR, year);
74 c.set(Calendar.MONTH, month);
75 c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
76 String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
77
78TextView textView = (TextView) findViewById(R.id.textView);
79textView.setText(currentDateString);
80
81
82
83DatePicker Alternative (Simple)
84MainActivity.java
85
86TextView tv;
87Calendar mCurrentDate;
88int day,month,year;
89
90
91tv = (TextView)findViewById(R.id.textView);
92mCurrentDate = Calendar.getInstance();
93
94day = mCurrentDate.get(Calendar.DAY_OF_MONTH);
95month = mCurrentDate.get(Calendar.MONTH);
96year = mCurrentDate.get(Calendar.YEAR);
97month = month+1;
98tv.setText(day+"/"+month+"/"+year);
99
100tv.setOnClickListener(new View.OnClickListener(){
101@Override
102public void onClick(View v){
103DatePickerDialog datePickerDialog = new DatePickerDialog( MainActivity.this,new DatePickerDialog.OnDateSetListener(){
104@Override
105public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){
106monthOfYear = monthOfYear + 1;
107tv.setText(dayOfMonth+"/"+monthOfYear+"/"+year);
108}
109},year, month, day);
110datePickerDialog.show();
111}
112});
113
114
115Notification
116Create a button
117MainActivity.java
118
119NotificationCompat.Builder notification;
120private static final int uniqueID = 45612;
121
122onCreate()
123notification = new NotificationCompat.Builder(this);
124notification.setAutoCancel(true);
125
126public void buckysButtonClicked(View view){
127notification.setSmallIcon(R.drawable.ic_Launder);
128notification.setTicker("This is the ticker");
129notification.setWhen(System.currentTimeMillis());
130notification.setContentTitle("Here is the title");
131notification.setContentText("I am the body of your notification");
132
133Intent intent = new Intent(this,MainActivity.class);
134PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
135notification.setContentIntent(pendingIntent);
136
137NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
138nm.notify(uniqueID, notification.build());
139}
140
141Notification Alternate
142Create a button and in the OnClick
143
144NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this).setDefaults(NotificationCompat.DEFAULT_ALL)
145 .setSmallIcon(R.drawable.stlsm)
146 .setContentTitle("Notification from Sanktips")
147 .setContentText("Hello and welcome to Sanktips");
148NotificationManager notificationManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
149notificationManager.notify(1,notificationBuilder.build());
150
151
152Broadcast Send Two programs
153First Program
154Create Button
155onClick:
156public void sendOutBroadcast(View view){
157Intent i = new Intent();
158i.setAction("package name");
159i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
160sendBroadcast(i);
161}
162
163Second Program(AddNo activity)
164Right click JavaFolder->New->Other->Broadcast Receiver
165Classname:ReceiveBroadcast. Tick Exported, Enabled
166
167ReceiveBroadcast.java
168onReceive delete default add this
169Toast.makeText(context,"Broadcast has been received!",Toast.LENGTH_LONG).show();
170AndroidManifest.xml
171<application>
172<receiver>...
173<intent-filter>
174 <action android:name="FirstProgramPackage"></action>
175</intent-filter>
176</receiver>
177Edit Run Configuration:-Activity->Do not launch activity.
178
179
180Radio Button
181
182XML
183<RadioGroup>
184 id:radioGroup
185 android:layout_width="wrap_content"
186 android:layout_height="wrap_content"
187<RadioButton>
188 id=radio_one
189 onClick="checkButton"
190 android:layout_width="wrap_content"
191 android:layout_width="wrap_content"/>
192<RadioButton>id=radio_two
193 onClick="checkButton"/>
194</RadioGroup>
195
196MainActivity.java
197RadioGroup radioGroup;
198RadioButton radioButton;
199TextView textView;
200
201onCreate
202radioGroup = findViewById(R.id.radioGroup);
203textView = findViewById(R.id.text_view_selected);
204
205Button buttonApply = findViewById(R.id.button_apply);
206buttonApply.setOnClickListener(new View.OnClickListener(){
207
208@Override
209public void onClick(View v){
210int radioId = radioGroup.getCheckedRadioButtonId();
211radioButton = findViewById(radioId);
212textView.setText("Your choice: " + radioButton.getText());
213}
214});
215
216public void checkButton(View v){
217int radioId = radioGroup.getCheckedRadioButtonId();
218radioButton = findViewById(radioId);
219Toast.makeText(this,"Selected Radio Button: " + radioButton.getText(), Toast.LENGTH_SHORT).show();
220}
221
222Check Box
223public void onClick(View v){
224StringBuffer result = new StringBuffer();
225result.append("Dog:").append(check1.isChecked());
226result.append("Cat:").append(check2.isChecked());
227Toast.makeText( MainActivity.this, result.toString());
228}
229
230
231SQLite Database
232
233To check DB. Tools->Android->Android Device Monitor->Package name or App name->FileExplorer->data->data->Package name or App name ->databases->Student.db
234Create database and tables
235Create new java class DatabaseHelper.java extends SQLiteOpenHelper{
236(Right click on the red button and Create Constructor matching super. Choose first one SQLiteOpenHelper
237
238DatabaseHelper.java
239package com.example.programmingknowledge.sqliteapp;
240
241import android.content.ContentValues;
242import android.content.Context;
243import android.database.Cursor;
244import android.database.sqlite.SQLiteDatabase;
245import android.database.sqlite.SQLiteOpenHelper;
246
247/**
248 * Created by ProgrammingKnowledge on 4/3/2015.
249 */
250public class DatabaseHelper extends SQLiteOpenHelper {
251 public static final String DATABASE_NAME = "Student.db";
252 public static final String TABLE_NAME = "student_table";
253 public static final String COL_1 = "ID";
254 public static final String COL_2 = "NAME";
255 public static final String COL_3 = "SURNAME";
256 public static final String COL_4 = "MARKS";
257
258 public DatabaseHelper(Context context) {
259 super(context, DATABASE_NAME, null, 1);
260 }
261
262 @Override
263 public void onCreate(SQLiteDatabase db) {
264 db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER)");
265 }
266
267 @Override
268 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
269 db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
270 onCreate(db);
271 }
272
273 public boolean insertData(String name,String surname,String marks) {
274 SQLiteDatabase db = this.getWritableDatabase();
275 ContentValues contentValues = new ContentValues();
276 contentValues.put(COL_2,name);
277 contentValues.put(COL_3,surname);
278 contentValues.put(COL_4,marks);
279 long result = db.insert(TABLE_NAME,null ,contentValues);
280 if(result == -1)
281 return false;
282 else
283 return true;
284 }
285
286 public Cursor getAllData() {
287 SQLiteDatabase db = this.getWritableDatabase();
288 Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
289 return res;
290 }
291
292 public boolean updateData(String id,String name,String surname,String marks) {
293 SQLiteDatabase db = this.getWritableDatabase();
294 ContentValues contentValues = new ContentValues();
295 contentValues.put(COL_1,id);
296 contentValues.put(COL_2,name);
297 contentValues.put(COL_3,surname);
298 contentValues.put(COL_4,marks);
299 db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
300 return true;
301 }
302
303 public Integer deleteData (String id) {
304 SQLiteDatabase db = this.getWritableDatabase();
305 return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
306 }
307}
308
309
310MainActivity.java{
311
312package com.example.programmingknowledge.sqliteapp;
313
314import android.app.AlertDialog;
315import android.database.Cursor;
316import android.support.v7.app.ActionBarActivity;
317import android.os.Bundle;
318import android.view.Menu;
319import android.view.MenuItem;
320import android.view.View;
321import android.widget.Button;
322import android.widget.EditText;
323import android.widget.Toast;
324
325
326public class MainActivity extends ActionBarActivity {
327 DatabaseHelper myDb;
328 EditText editName,editSurname,editMarks ,editTextId;
329 Button btnAddData;
330 Button btnviewAll;
331 Button btnDelete;
332
333 Button btnviewUpdate;
334 @Override
335 protected void onCreate(Bundle savedInstanceState) {
336 super.onCreate(savedInstanceState);
337 setContentView(R.layout.activity_main);
338 myDb = new DatabaseHelper(this);
339
340 editName = (EditText)findViewById(R.id.editText_name);
341 editSurname = (EditText)findViewById(R.id.editText_surname);
342 editMarks = (EditText)findViewById(R.id.editText_Marks);
343 editTextId = (EditText)findViewById(R.id.editText_id);
344 btnAddData = (Button)findViewById(R.id.button_add);
345 btnviewAll = (Button)findViewById(R.id.button_viewAll);
346 btnviewUpdate= (Button)findViewById(R.id.button_update);
347 btnDelete= (Button)findViewById(R.id.button_delete);
348 AddData();
349 viewAll();
350 UpdateData();
351 DeleteData();
352 }
353 public void DeleteData() {
354 btnDelete.setOnClickListener(
355 new View.OnClickListener() {
356 @Override
357 public void onClick(View v) {
358 Integer deletedRows = myDb.deleteData(editTextId.getText().toString());
359 if(deletedRows > 0)
360 Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
361 else
362 Toast.makeText(MainActivity.this,"Data not Deleted",Toast.LENGTH_LONG).show();
363 }
364 }
365 );
366 }
367 public void UpdateData() {
368 btnviewUpdate.setOnClickListener(
369 new View.OnClickListener() {
370 @Override
371 public void onClick(View v) {
372 boolean isUpdate = myDb.updateData(editTextId.getText().toString(),
373 editName.getText().toString(),
374 editSurname.getText().toString(),editMarks.getText().toString());
375 if(isUpdate == true)
376 Toast.makeText(MainActivity.this,"Data Update",Toast.LENGTH_LONG).show();
377 else
378 Toast.makeText(MainActivity.this,"Data not Updated",Toast.LENGTH_LONG).show();
379 }
380 }
381 );
382 }
383 public void AddData() {
384 btnAddData.setOnClickListener(
385 new View.OnClickListener() {
386 @Override
387 public void onClick(View v) {
388 boolean isInserted = myDb.insertData(editName.getText().toString(),
389 editSurname.getText().toString(),
390 editMarks.getText().toString() );
391 if(isInserted == true)
392 Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
393 else
394 Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
395 }
396 }
397 );
398 }
399
400 public void viewAll() {
401 btnviewAll.setOnClickListener(
402 new View.OnClickListener() {
403 @Override
404 public void onClick(View v) {
405 Cursor res = myDb.getAllData();
406 if(res.getCount() == 0) {
407 // show message
408 showMessage("Error","Nothing found");
409 return;
410 }
411
412 StringBuffer buffer = new StringBuffer();
413 while (res.moveToNext()) {
414 buffer.append("Id :"+ res.getString(0)+"\n");
415 buffer.append("Name :"+ res.getString(1)+"\n");
416 buffer.append("Surname :"+ res.getString(2)+"\n");
417 buffer.append("Marks :"+ res.getString(3)+"\n\n");
418 }
419
420 // Show all data
421 showMessage("Data",buffer.toString());
422 }
423 }
424 );
425 }
426
427 public void showMessage(String title,String Message){
428 AlertDialog.Builder builder = new AlertDialog.Builder(this);
429 builder.setCancelable(true);
430 builder.setTitle(title);
431 builder.setMessage(Message);
432 builder.show();
433 }
434
435
436 @Override
437 public boolean onCreateOptionsMenu(Menu menu) {
438 // Inflate the menu; this adds items to the action bar if it is present.
439 getMenuInflater().inflate(R.menu.menu_main, menu);
440 return true;
441 }
442
443 @Override
444 public boolean onOptionsItemSelected(MenuItem item) {
445 // Handle action bar item clicks here. The action bar will
446 // automatically handle clicks on the Home/Up button, so long
447 // as you specify a parent activity in AndroidManifest.xml.
448 int id = item.getItemId();
449
450 //noinspection SimplifiableIfStatement
451 if (id == R.id.action_settings) {
452 return true;
453 }
454
455 return super.onOptionsItemSelected(item);
456 }
457}
458
459Checking particular record
460 Cursor cursor = null;
461 String sql ="SELECT PID FROM "+TableName+" WHERE PID="+pidValue;
462 cursor= db.rawQuery(sql,null);
463 Log("Cursor Count : " + cursor.getCount());
464
465 if(cursor.getCount()>0){
466 //PID Found
467 }else{
468 //PID Not Found
469 }
470 cursor.close();
471
472
473
474Firebase
475
476package com.test.test01;
477
478import android.support.v7.app.AppCompatActivity;
479import android.os.Bundle;
480import android.view.View;
481import android.widget.Button;
482import android.widget.EditText;
483import android.widget.Spinner;
484import android.widget.Toast;
485
486import com.google.firebase.database.DatabaseReference;
487import com.google.firebase.database.FirebaseDatabase;
488
489public class MainActivity extends AppCompatActivity {
490
491 EditText editTextName;
492 Button buttonAdd;
493 Spinner spinnerGenres;
494
495 DatabaseReference databaseArtists;
496
497 @Override
498 protected void onCreate(Bundle savedInstanceState) {
499 super.onCreate(savedInstanceState);
500 setContentView(R.layout.activity_main);
501
502 databaseArtists = FirebaseDatabase.getInstance().getReference("artist");
503
504 editTextName = (EditText)findViewById(R.id.editTextName);
505 buttonAdd = (Button)findViewById(R.id.buttonAddArtist);
506 spinnerGenres = (Spinner)findViewById(R.id.spinnerGenres);
507
508 buttonAdd.setOnClickListener(new View.OnClickListener() {
509 @Override
510 public void onClick(View view) {
511 addArtist();
512 }
513 });
514 }
515
516 private void addArtist(){
517 String name = editTextName.getText().toString().trim();
518 String genre = spinnerGenres.getSelectedItem().toString();
519
520 String id = databaseArtists.push().getKey();
521
522
523 Artist artist = new Artist(id,name,genre);
524 databaseArtists.child(id).setValue(artist);
525 Toast.makeText(this,"Artist added",Toast.LENGTH_SHORT).show();
526
527
528 }
529
530}
531
532Artist.java:
533package com.test.test01;
534
535public class Artist {
536 String artistId;
537 String artistName;
538 String artistGenre;
539
540 public Artist(){
541
542 }
543
544 public Artist(String artistId, String artistName, String artistGenre) {
545 this.artistId = artistId;
546 this.artistName = artistName;
547 this.artistGenre = artistGenre;
548 }
549
550 public String getArtistId() {
551 return artistId;
552 }
553
554 public String getArtistName() {
555 return artistName;
556 }
557
558 public String getArtistGenre() {
559 return artistGenre;
560 }
561}
562
563
564
565Firebase
566https://www.youtube.com/watch?v=EM2x33g4syY&t=5s
567
568
569GridView
570
571MainActivity.java
572package com.test.gridview;
573
574import android.support.v7.app.AppCompatActivity;
575import android.os.Bundle;
576import android.widget.GridView;
577
578public class MainActivity extends AppCompatActivity {
579
580 GridView gridView;
581 String[] values = {"Java","CSS","HTML","JS"};
582
583
584 @Override
585 protected void onCreate(Bundle savedInstanceState) {
586 super.onCreate(savedInstanceState);
587 setContentView(R.layout.activity_main);
588
589 gridView= (GridView) findViewById(R.id.grid);
590
591 GridAdapter gridAdapter = new GridAdapter(this,values);
592 gridView.setAdapter(gridAdapter);
593 }
594}
595
596
597activity_main.xml
598<?xml version="1.0" encoding="utf-8"?>
599<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
600 xmlns:app="http://schemas.android.com/apk/res-auto"
601 xmlns:tools="http://schemas.android.com/tools"
602 android:layout_width="match_parent"
603 android:layout_height="match_parent"
604 tools:context=".MainActivity">
605
606 <GridView
607 android:id="@+id/grid"
608 android:layout_width="fill_parent"
609 android:layout_height="wrap_content"
610 android:numColumns="3"/>
611
612</LinearLayout>
613
614GridAdapter.java
615package com.test.gridview;
616
617import android.content.Context;
618import android.text.Layout;
619import android.view.LayoutInflater;
620import android.view.View;
621import android.view.ViewGroup;
622import android.widget.BaseAdapter;
623import android.widget.TextView;
624
625public class GridAdapter extends BaseAdapter {
626
627 Context context;
628 private final String[] values;
629 View view;
630 LayoutInflater layoutInflater;
631
632 public GridAdapter(Context context, String[] values) {
633 this.context = context;
634 this.values = values;
635 }
636
637 @Override
638 public int getCount() {
639 return values.length;
640 }
641
642 @Override
643 public Object getItem(int i) {
644 return null;
645 }
646
647 @Override
648 public long getItemId(int i) {
649 return 0;
650 }
651
652 @Override
653 public View getView(int position, View convertView, ViewGroup parent) {
654 layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
655
656 if(convertView == null){
657 view = new View(context);
658 view = layoutInflater.inflate(R.layout.single_item,null);
659
660 TextView textView = (TextView)view.findViewById(R.id.textView);
661 textView.setText(values[position]);
662 }
663 return view;
664 }
665}
666
667single_item.xml
668<?xml version="1.0" encoding="utf-8"?>
669<LinearLayout
670 xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
671 android:layout_height="match_parent"
672 android:padding="8dp"
673 android:gravity="center">
674
675 <TextView
676 android:id="@+id/textView"
677 android:gravity="center"
678 android:layout_width="wrap_content"
679 android:layout_height="wrap_content" />
680
681</LinearLayout>