0% found this document useful (0 votes)
7 views2 pages

MP cheat_2

Uploaded by

FF Panda Gaming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

MP cheat_2

Uploaded by

FF Panda Gaming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Using Strings and String Arrays in Android RETRIEVING CONTENTS FROM THE REMOTE SERVER

Strings and string arrays are commonly used in Android to define text that can be Our application uses the Volley Library to communicate with the server. Volley is
reused throughout the application. These are typically stored in the
res/values/strings.xml file. an HTTP library that makes networking for Android apps easier and most
Defining a String Resource Strings: Define reusable text in strings.xml. importantly, faster.
<resources> Volley offers the following benefits:
<string name="app_name">My Application</string>  Automatic scheduling of network requests.
<string name="welcome_message">Welcome to My App!</string>
 Multiple concurrent network connections.
</resources>
Use in xml layout  Transparent disk and memory response caching.
<TextView  Support for request prioritization.
android:layout_width="wrap_content"  Cancellation request API. You can cancel a single request or set blocks or scopes
android:layout_height="wrap_content" of requests to cancel.
android:text="@string/welcome_message" />
 Ease of customization, for example, for retry and back off.
Defining a String Array  Strong ordering that makes it easy to correctly populate your Ul with data
String Arrays: Define lists of strings in strings.xml, which can be used in lists or fetched asynchronously from the network.
other UI components.  Debugging and tracing tools.
<resources>
<string-array name="programming_languages"> To use Volley in your application, we need to add the following dependency to
<item>Java</item> our project:
<item>Kotlin</item> dependencies {
<item>Python</item> …..
<item>C++</item> implementation 'com.android.volley: volley: 1.1.1'
</string-array>
</resources> }
Use in xml layout Also, to use Volley, you must add the android. permission.INTERNET permission
<Spinner to your app's manifest. Without this, your app won't be able to connect to the
android:id="@+id/spinner" network.
android:layout_width="wrap_content" <uses-permission android:name="android.permission. INTERNET"/>
android:layout_height="wrap_content"
Code//:
android:entries="@array/programming_languages" />
public void volleyRequest() {
//Instantiate the Request.Queue.
develop an android application to display alert dialog box. <?xml version="1.0" encoding="utf-8"?> RequestQueue queue Volley.newRequestQueue(this);
UI Layout: Added a button to activity_main.xml. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" //url for localhost
Button Functionality: Set up an OnClickListener in MainActivity.java to show an android:layout_width="match_parent" String url "http://10.0.2.2/myproject/getdata.php";
alert dialog. android:layout_height="match_parent" // Request a string response from the provided URL.
AlertDialog: Used AlertDialog.Builder to create and show the dialog with title, android:orientation="vertical" StringRequest stringRequest new StringRequest (Request.Method.GET, url,
message, and buttons. android:padding="16dp"> new Response. Listener<String> () {
XML file <Spinner @Override
<?xml version="1.0" encoding="utf-8"?> android:id="@+id/spinner" public void onResponse (String response) (
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" //displaying response string in logcat
android:layout_width="match_parent" android:layout_height="wrap_content" Log.d("result", response):
android:layout_height="match_parent"> android:spinnerMode="dropdown" /> }
<Button </LinearLayout> },new Response.ErrorListener() {
android:id="@+id/showDialogButton" String.xml file @Override
android:layout_width="wrap_content" <resources> public void onErrorResponse (VolleyError error) {
android:layout_height="wrap_content" <string name="app_name">SimpleSpinnerExample</string> //displaying error response message
android:text="Show Alert Dialog" <string-array name="programming_languages"> Log.d("exception", error.toString());
android:layout_centerInParent="true" /> <item>Java</item> }
</RelativeLayout> <item>Kotlin</item> });
<item>Python</item> // Add the request to the Request.Queue.
Java File <item>C++</item> queue.add(stringRequest);
import android.os.Bundle; <item>JavaScript</item> }
import android.view.View; <item>Swift</item> Output :- we can see the retrieve data in log file
import android.widget.Button; <item>Ruby</item> Displaying Retrieved data in RecyclerView
import androidx.appcompat.app.AlertDialog; <item>PHP</item> //creating xml file json_example.xml
import androidx.appcompat.app.AppCompatActivity; </string-array>
public class MainActivity extends AppCompatActivity { </resources> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
what is menu ? Explain its types with syntax? and a program to display option xmlns:android="http://schemas.android.com/apk/res/android"
menu. android:layout_width="match_parent"
what is menu ? Explain its types with syntax? and a program to display option import android.Manifest;
In Android, a menu is a user import android.content.pm.PackageManager;
interface element that provides a set of options or
menu. import
actions android.location.Location;
for users to choose from.import Menusandroid.os.Bundle;
are commonly used for navigation, android:layout_height="match_parent"
In Android, a menu is a user interface element that provides a set of options or configuration, and other import
actionsandroidx.annotation.NonNull;
in an app. There are three primary types of android:padding="5dp">
import android.widget.*;
actions for users to choose from. Menus are commonly used for navigation, menus in Android:
configuration, and other actions in an app. There are three primary types of import androidx.appcompat.app.AppCompatActivity;
2. Context Menu <androidx.recyclerview.widget.RecyclerView
menus in Android: import
Purpose: androidx.core.app.ActivityCompat;
The context menu provides options related to the specific item or view
2. Context Menu import androidx.core.content.ContextCompat; android:id="@+id/recyclerview"
that was long-pressed. It appears as a floating menu near the item.
Purpose: The context menu provides options related to the specific item or view import
Appearscom.google.android.gms.location.*;
on long press of a view, provides options related to that view. Register android:layout_width="match_parent"
that was long-pressed. It appears as a floating menu near the item. contextcom.google.android.gms.tasks.*;
menu with registerForContextMenu and handle in android:layout_height="wrap_content"/>
import
Appears on long press of a view, provides options related to that view. Register onCreateContextMenu </RelativeLayout>
context menu with registerForContextMenu and handle in public class MainActivityand onContextItemSelected.
extends AppCompatActivity {
Syntax
onCreateContextMenu and onContextItemSelected. private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
registerForContextMenu(textView);
Syntax private FusedLocationProviderClient fusedLocationClient; //creating list items.xml
@Override
registerForContextMenu(textView); private TextView
public void locationTextView;
onCreateContextMenu(ContextMenu menu, View v, <?xml version="1.0" encoding="utf-8"?>
@Override ContextMenuInfo menuInfo) { <RelativeLayout
@Override
public void onCreateContextMenu(ContextMenu menu, View v, super.onCreateContextMenu(menu, v, menuInfo); xmlns:android="http://schemas.android.com/apk/res/android"
ContextMenuInfo menuInfo) { protected void onCreate(Bundle savedInstanceState) {
getMenuInflater().inflate(R.menu.context_menu, menu); android:layout_width="match_parent"
super.onCreateContextMenu(menu, v, menuInfo); } super.onCreate(savedInstanceState); android:layout_height="wrap_content">
getMenuInflater().inflate(R.menu.context_menu, menu); setContentView(R.layout.activity_main);
} locationTextView
3. Popup Menu = findViewById(R.id.locationTextView);
Purpose: The popup menu is a small menu that appears anchored to a view and
fusedLocationClient=LocationServices.getFusedLocationProviderClient(this); <TextView
3. Popup Menu is used to show a list of actions or options. android:id="@+id/txtId"
Purpose: The popup menu is a small menu that appears anchored to a view and if (ContextCompat.checkSelfPermission(this,
Appears anchored to a view, used for local actions. Define in res/menu and show android:layout_width="wrap_content"
is used to show a list of actions or options. Manifest.permission.ACCESS_FINE_LOCATION)
with PopupMenu class.
Appears anchored to a view, used for local actions. Define in res/menu and show android:layout_height="wrap_content"
public class MainActivity extends AppCompatActivity { {
== PackageManager.PERMISSION_GRANTED)
with PopupMenu class. getLastLocation();
@Override android:textSize="20sp"
public class MainActivity extends AppCompatActivity { protected android:layout_margin="10dp"
} else { void onCreate(Bundle savedInstanceState) {
@Override super.onCreate(savedInstanceState); android:text="Id"
protected void onCreate(Bundle savedInstanceState) { ActivityCompat.requestPermissions(this,
setContentView(R.layout.activity_main); android:textStyle="bold"/>
super.onCreate(savedInstanceState); Buttonnew String[]{Manifest.permission.ACCESS_FINE_LOCATION},
button = findViewById(R.id.showPopupButton);
setContentView(R.layout.activity_main); LOCATION_PERMISSION_REQUEST_CODE);
button.setOnClickListener(v -> { }}
Button button = findViewById(R.id.showPopupButton); @Override
PopupMenu popupMenu = new PopupMenu(MainActivity.this, v); <TextView
button.setOnClickListener(v -> { MenuInflater inflater = popupMenu.getMenuInflater(); android:id="@+id/txtName"
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
PopupMenu popupMenu = new PopupMenu(MainActivity.this, v); inflater.inflate(R.menu.popup_menu, android:layout_width="wrap_content"
MenuInflater inflater = popupMenu.getMenuInflater(); permissions, @NonNull int[] grantResults) { popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(item -> { android:layout_height="wrap_content"
inflater.inflate(R.menu.popup_menu, popupMenu.getMenu()); if (requestCode == LOCATION_PERMISSION_REQUEST_CODE
switch (item.getItemId()) {
popupMenu.setOnMenuItemClickListener(item -> { &&casegrantResults.length >0 android:textSize="20sp"
R.id.popup_item1:
switch (item.getItemId()) { && grantResults[0] ==1PackageManager.PERMISSION_GRANTED) { android:textStyle="bold"
// Handle Option
case R.id.popup_item1: return true; android:layout_toRightOf="@+id/txtId"
getLastLocation();
// Handle Option 1 android:layout_marginTop="10dp"
return true; } else { case R.id.popup_item2:
// Handle Option 2 android:text="Name"/>
case R.id.popup_item2: Toast.makeText(this,
return true; "Location permission is required",
// Handle Option 2 Toast.LENGTH_SHORT).show();
default: }}
return true; private voidreturn
getLastLocation() { <TextView
false;
default: } }); android:id="@+id/txtAddress"
fusedLocationClient.getLastLocation()
return false; android:layout_width="wrap_content"
} }); .addOnSuccessListener(this, location -> {
popupMenu.show(); }); } } android:layout_height="wrap_content"
if (location != null) {
popupMenu.show(); }); } } android:textSize="20sp"
1. Options locationTextView.setText(String.format("Latitude:
Menu %f\nLongitude: %f",
location.getLatitude(), location.getLongitude())); android:layout_marginLeft="10dp"
Purpose: The options menu is the primary menu of an activity, typically accessed
1. Options Menu by pressing the{ menu button (hardware or software). It is used to display options android:layout_below="@+id/txtName"
} else
Purpose: The options menu is the primary menu of an activity, typically accessed that are relevant to the current activity. android:text="Address"/>
by pressing the menu button (hardware or software). It is used to display options locationTextView.setText("Location not available");
Appears in the app bar, used for global actions or settings. Define in res/menu </RelativeLayout>
that are relevant to the current activity. and handle } });in onCreateOptionsMenu and onOptionsItemSelected.
Appears in the app bar, used for global actions or settings. Define in res/menu } }
and handle in onCreateOptionsMenu and onOptionsItemSelected.
Creating RecyclerViewAdapter.java SQLite is a lightweight, disk-based database management system that doesn't
import android.app.Activity; require a separate server process. It is designed to be embedded into applications.
import android.view.LayoutInflater; Here’s a detailed look at its features, advantages, and disadvantages: Features
import android.view.View; 1. Serverless: SQLite does not require a separate server process. The database is
import android.view.ViewGroup; integrated directly into the application.
import android.widget.TextView; 2. Zero Configuration: There’s no setup or administration required to use SQLite. It
import androidx.recyclerview.widget.RecyclerView; requires no configuration, making it simple to use.
import java.util.ArrayList; 3. Self-contained: The database is stored in a single file, which is portable and easy
public class RecyclerViewAdapter extends to manage.
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { 4. Cross-platform: SQLite is available on many platforms, including Windows,
private Activity context; macOS, Linux, iOS, and Android.
private ArrayList<DataModel> data; 5. Compact Size: SQLite is small in size and can be embedded into applications with
public RecyclerViewAdapter(Activity context, ArrayList<DataModel> data) { minimal overhead.
this.context = context; Advantages
this.data = data; 1. Lightweight: Its small footprint makes it ideal for applications with limited
} resources, like mobile apps or embedded systems.
@Override 2. Ease of Use: Simple to integrate and use with minimal setup required. Ideal for
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { small to medium-sized projects.
LayoutInflater layoutInflater = LayoutInflater.from(context); 3. Portability: The entire database is stored in a single file, making it easy to copy,
View listItem = layoutInflater.inflate(R.layout.list_items, parent, false); move, or back up.
return new ViewHolder(listItem); 4. Performance: SQLite can be very fast for read-heavy operations and small to
} medium-sized datasets.
@Override 5. Low Maintenance: No need for regular database administration or tuning.
public void onBindViewHolder(ViewHolder holder, int position) { Disadvantages
DataModel current = data.get(position); 1. Concurrency Limitations: While SQLite handles concurrency with database-level
holder.txtId.setText(String.valueOf(current.getId())); locking, it is not as performant for high-concurrency applications as server-based
holder.txtName.setText(current.getName()); databases like MySQL or PostgreSQL.
holder.txtAddress.setText(current.getAddress()); 2. Size Limitations: Although SQLite can handle databases up to 140 terabytes, it
} might not be suitable for extremely large datasets or high transaction volumes.
@Override 3. Lack of Advanced Features: It lacks some advanced features found in full-fledged
public int getItemCount() { database systems, such as user management, fine-grained access control, and
return data.size(); complex replication.
} 4. Single-File Database: While portability is a strength, storing the
public static class ViewHolder extends RecyclerView.ViewHolder { entire database in a single file can be a drawback if the file
public TextView txtId; Java file become @Override
public TextView txtName; package com.example.simplespinnerexample; protected void onCreate(Bundle savedInstanceState) {
public TextView txtAddress; public ViewHolder(View itemView) {
import android.os.Bundle; import android.widget.*; super.onCreate(savedInstanceState);
super(itemView);
txtId = itemView.findViewById(R.id.txtId); import androidx.appcompat.app.AppCompatActivity; setContentView(R.layout.activity_main);
txtName = itemView.findViewById(R.id.txtName); public class MainActivity extends AppCompatActivity { Button showDialogButton = findViewById(R.id.showDialogButton);
txtAddress = itemView.findViewById(R.id.txtAddress); @Override showDialogButton.setOnClickListener(new View.OnClickListener() {
} protected void onCreate(Bundle savedInstanceState) { @Override
} super.onCreate(savedInstanceState); public void onClick(View v) {
}
setContentView(R.layout.activity_main); showAlertDialog();
Creating JsonExample.java // Find the Spinner in the layout }
import android.os.Bundle; Spinner spinner = findViewById(R.id.spinner); });
import android.util.Log; // Create an ArrayAdapter to hold the items for the Spinner }
import androidx.appcompat.app.AppCompatActivity;
ArrayAdapter<CharSequence> adapter = private void showAlertDialog() {
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; ArrayAdapter.createFromResource( new AlertDialog.Builder(this)
import com.android.volley.Request; this, R.array.programming_languages, .setTitle("Alert Dialog")
import com.android.volley.RequestQueue; android.R.layout.simple_spinner_item); .setMessage("This is an alert dialog example.")
import com.android.volley.Response; adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdow .setPositiveButton("OK", (dialog, which) -> dialog.dismiss())
import com.android.volley.VolleyError; n_item); .setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss())
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley; spinner.setAdapter(adapter); .create()
import org.json.JSONArray; spinner.setOnItemSelectedListener((parent, view, position, id) -> { .show();
import org.json.JSONObject; // Get the selected item }
import java.util.ArrayList; String selectedLanguage = parent.getItemAtPosition(position).toString(); }
Toast.makeText(MainActivity.this, "Selected: " + selectedLanguage,
public class JsonExample extends AppCompatActivity {
private RecyclerView recyclerView; Toast.LENGTH_SHORT).show();
private RecyclerView.Adapter recyclerAdapter; });
private RecyclerView.LayoutManager layoutManager; }
@Override }
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.json_example); How to generate signed APK? Write a program to locate user's current location Creating a menu XML file in the res/menu directory (e.g.,
recyclerView = findViewById(R.id.recyclerview); (write only java and manifest) res/menu/main_menu.xml).
// Call the method to fetch data <?xml version="1.0" encoding="utf-8"?>
Generating a Signed APK
volleyRequest(); <menu xmlns:android="http://schemas.android.com/apk/res/android">
} 1. Open Your Project: Launch Android Studio and open your project. <item
public void volleyRequest() { 2. Build Signed APK: android:id="@+id/action_settings"
// Instantiate the RequestQueue . Go to the Build menu and select Generate Signed Bundle / APK. android:title="Settings"
RequestQueue queue = Volley.newRequestQueue(this); . Choose APK and click Next. android:orderInCategory="100"
// URL for localhost android:showAsAction="never" />
. If you don’t have a keystore, create a new one by clicking Create new. Fill in the
String url = "http://10.0.2.2/myproject/getdata.php"; <item
// Request a string response from the provided URL required information (keystore path, password, key alias, etc.). android:id="@+id/action_about"
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, . If you already have a keystore, select Choose existing and provide the keystore android:title="About"
new Response.Listener<String>() { details. android:orderInCategory="200"
@Override . Select the Release build type and click Finish. android:showAsAction="never" />
public void onResponse(String response) { </menu>
. Android Studio will build and sign the APK. The signed APK will be available in the
// Passing data for decoding
decodeJson(response); app/release directory of your project.
Program to locate import android.os.Bundle;
}
}, Update AndroidManifest.xml import android.view.Menu;
new Response.ErrorListener() { <manifest xmlns:android="http://schemas.android.com/apk/res/android" import android.view.MenuItem;
@Override import androidx.appcompat.app.AppCompatActivity;
package="com.example.locationapp">
public void onErrorResponse(VolleyError error) {
// Displaying error response message <application ….>
<activity android:name=".MainActivity"> public class MainActivity extends AppCompatActivity {
Log.d("exception", error.toString());
} <intent-filter>
}); <action android:name="android.intent.action.MAIN" /> @Override
<category android:name="android.intent.category.LAUNCHER" /> protected void onCreate(Bundle savedInstanceState) {
// Add the request to the RequestQueue super.onCreate(savedInstanceState);
queue.add(stringRequest); </intent-filter>
</activity> setContentView(R.layout.activity_main);
}
public void decodeJson(String response) { </application> }
try { <!-- Permissions for location access -->
ArrayList<DataModel> data = new ArrayList<>(); @Override
<uses-permission
JSONObject result = new JSONObject(response); public boolean onCreateOptionsMenu(Menu menu) {
JSONArray array = result.getJSONArray("data"); android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission getMenuInflater().inflate(R.menu.main_menu, menu);
for (int i = 0; i < array.length(); i++) {
// Fetching each row android:name="android.permission.ACCESS_COARSE_LOCATION" /> return true;
JSONObject student = array.getJSONObject(i); </manifest> }
int sid = student.getInt("sid");
Update activity_main.xml
String name = student.getString("name"); @Override
String address = student.getString("address"); <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" public boolean onOptionsItemSelected(MenuItem item) {
DataModel dataModel = new DataModel(sid, name, address);
data.add(dataModel); android:layout_width="match_parent" switch (item.getItemId()) {
} android:layout_height="match_parent"> case R.id.action_settings:
// Plotting data in RecyclerView // Handle settings action
layoutManager = new LinearLayoutManager(this); return true;
recyclerView.setLayoutManager(layoutManager); <TextView
android:id="@+id/locationTextView" case R.id.action_about:
recyclerAdapter = new RecyclerViewAdapter(JsonExample.this, data);
recyclerView.setAdapter(recyclerAdapter); android:layout_width="wrap_content" // Handle about action
android:layout_height="wrap_content" return true;
} catch (Exception ex) { default:
android:text="Location information will appear here"
Log.d("exception", ex.toString()); return super.onOptionsItemSelected(item);
} android:layout_centerInParent="true"
android:textSize="18sp" /> }
}
} </RelativeLayout> }
}

You might also like