In need to get a LinearLayout (Any layout file from layout folder by name) and add to current Layout |
package com.pritom; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; public class TestActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home_main_page); LinearLayout mainLayout = this.findViewById(R.id.mainLayoutScrollView); /* If you want to remove all views from current layout */ if (mainLayout.getChildCount() > 0) mainLayout.removeAllViews(); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); /* There must be a layout file named 'home_content.xml' in layout folder */ View view = inflater.inflate(R.layout.home_content, null); mainLayout.addView(view); } } |
Showing posts with label android. Show all posts
Showing posts with label android. Show all posts
Thursday, October 25, 2018
Android: Get linearLayout (Any layout file from layout folder by name) and add to current Layout
Saturday, October 6, 2018
Android Activity as a dialog popup box
Let say I have an Activity named PasswordCreatePage which has child dialogs as well. Now, I want to display this activity as a dialog for another activity. At this stage we need something special to do. First let see PasswordCreatePage class below: |
package com.pritom.kumar; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup; import android.view.Window; public class PasswordCreatePage extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If you want to hide title bar this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Setting dialog box title setTitle(R.string.set_password); // Setting layout page at this stage setContentView(R.layout.password_create_page); // If you want to finish this activity on touch outside of this dialog this.setFinishOnTouchOutside(false); // Setting dialog box width 100% and height as content height getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } |
Now we will create/modify a theme in PROJECT/RES/VALUES named STYLES.XML, add below content to the file (actually this file describes the style of the dialog box): |
<style name="AlertDialogCustomWithTitle" parent="@android:style/Theme.Dialog"> <item name="android:buttonStyle">@style/ButtonColor</item> </style> |
At this stage we will create a layout page with below content (it's actually a simple layout page): |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/constraintLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_gravity="center" android:padding="10dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/password" /> </LinearLayout> |
Now we will put an entry to ANDROIDMANIFEST.XML related to our Activity: |
<activity android:name=".PasswordCreatePage" android:theme="@style/AlertDialogCustomWithTitle" android:excludeFromRecents="true"> </activity> |
We are done. If you open this activity, this will open as a Dialog Popup Box. |
Friday, October 5, 2018
Android: Last line of textview getting cut off / getting hide some parts of text view in LinearLayout
I have a horizontal LinearLayout containing a Checkbox followed by a TextView next to it. This LinearLayout is dynamically inflated multiple times in a fixed vertical LinearLayout contained within a RelativeLayout. |
The problem is the last line of the TextView gets cut in half. This happens when the dynamic text is long and spans more than one row. Below is my xml portion which causing the problem: |
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <CheckBox android:id="@+id/cbAllowTransferOnlyWifi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_gravity="fill" android:text="@string/transfer.over.wifi.only" /> </LinearLayout> |
The solution is to appliy a LayoutGravity to the TextView item like below: |
android:layout_gravity="fill" |
And this is the fix. |
Tuesday, October 2, 2018
Emulator: ERROR: x86 emulation currently requires hardware acceleration
I tried to run my Hello World application in Android Studio. I got the following error: |
* Emulator: ERROR: x86 emulation currently requires hardware acceleration!
* Please ensure Intel HAXM is properly installed and usable. * CPU acceleration status: HAX kernel module is not installed! |
So solution is as below: |
* Open SDK Manager (In Android Studio, go to Tools > Android > SDK Manager) and Download Intel x86 Emulator Accelerator (HAXM installer) if you haven't.
* Now go to your SDK directory C:\users\%USERNAME%\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager\ and run the file named intelhaxm-android.exe. * In case you get an error like "Intel virtualization technology (vt,vt-x) is not enabled". Go to your BIOS settings and enable Hardware Virtualization. * Restart Android Studio and then try to start the AVD again. |
Saturday, September 15, 2018
Android studio 3.X does not render xml file due to java class missing
java.lang.ClassNotFoundException: android.view.View$OnUnhandledKeyEventListener |
In my very first project is obviously Hello world and I just open android studio and click on the empty activity and then w8 for the build to finish but it doesn't render the app as I expected. I reinstalled android studios and JDK10. but it doesn't work. the project shows fine in virtual device and I can even edit hello world to any string, but in XML view, it just shows a white screen and its showing every time. Below is the stack trace: |
java.lang.ClassNotFoundException: android.view.View$OnUnhandledKeyEventListener at org.jetbrains.android.uipreview.ModuleClassLoader.load(ModuleClassLoader.java:180) at com.android.tools.idea.rendering.RenderClassLoader.findClass(RenderClassLoader.java:61) at org.jetbrains.android.uipreview.ModuleClassLoader.findClass(ModuleClassLoader.java:118) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at org.jetbrains.android.uipreview.ModuleClassLoader.loadClass(ModuleClassLoader.java:213) at android.support.v7.widget.ActionBarContainer.(ActionBarContainer.java:62) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:481) at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:264) at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:222) at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:209) at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:337) at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:348) at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:248) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:863) at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72) at android.view.LayoutInflater.rInflate(LayoutInflater.java:837) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at com.android.layoutlib.bridge.bars.BridgeActionBar.(BridgeActionBar.java:89) at com.android.layoutlib.bridge.bars.AppCompatActionBar.(AppCompatActionBar.java:68) at com.android.layoutlib.bridge.impl.Layout.createActionBar(Layout.java:277) at com.android.layoutlib.bridge.impl.Layout.(Layout.java:161) at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:288) at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:384) at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:193) at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:544) at com.android.tools.idea.rendering.RenderTask.lambda$inflate$3(RenderTask.java:678) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) |
First of all we are developing an app, so we don't need to face these types of issues because it has no valid reason to get such errors. So I suggest you use always stable version of every dependency, and this is because of unstable version using. |
The issue you faced was due to using alpha version of AppCompact library. Use stable version to get rid of this issue now and in future. |
FIRST Currently 27.1.1 is latest version of AppComactV7. You can see Maven Repo link to find out latest. final def SUPPORT_VERSION = "27.1.1" implementation "com.android.support:appcompat-v7:$SUPPORT_VERSION" implementation "com.android.support:design:$SUPPORT_VERSION" // use only if already using I use definitions to have same version for all support versions. Also ignore design library if you are not already using it. |
SECOND You also need to downgrade your compileSdkVersion & targetSdkVersion to remove some gradle warnings. compileSdkVersion 27 targetSdkVersion 27 |
Below is full example of build.gradle (Module:app) |
apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.hp.myapplication" minSdkVersion 15 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } final def SUPPORT_VERSION = "27.1.1" dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "com.android.support:appcompat-v7:$SUPPORT_VERSION" implementation "com.android.support:design:$SUPPORT_VERSION" implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.android.support:gridlayout-v7:27.1.1' } |
Emulator: ERROR: x86 emulation currently requires hardware acceleration
The problem is very simple and am going to solve that problem in very simple way. Problem is to lunch android app from Android Studio. The problem is as below described: |
|
First step to open SDK Manager (In Android Studio, go to Tools > Android > SDK Manager) and Download Intel x86 Emulator Accelerator (HAXM installer) if you haven't as below screen shot: |
|
Now go to your SDK directory C:\users\%USERNAME%\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager\ and run the file named intelhaxm-android.exe. This will almost fix your problem. In case you get an error like "Intel virtualization technology (vt,vt-x) is not enabled". Go to your BIOS settings and enable Hardware Virtualization. |
Restart Android Studio and then try to start the AVD again.
It might take a minute or 2 to show the emulator window. |
Friday, April 28, 2017
jQuery UI Sortable and Draggable NOT working on iPad, iPhone or Android
jQuery UI sortable, draggable, re-sizable and all others working fine on browsers with no problems, however when I test it on hand held devices such as iPad, iPod, iPhone and Android it doesn't work. I cannot drag the boxes or sort the order at all.
Touch Punch will fix this issue, and most other jQuery UI on touch device problems. They described the process as hack, but it it is a lifesaver too.
Also you can download library from here.
Touch Punch will fix this issue, and most other jQuery UI on touch device problems. They described the process as hack, but it it is a lifesaver too.
Also you can download library from here.
Thursday, June 4, 2015
Android: Update GUI field vlaue/display or show a message (toast) from Thread
Util Class
package com.pkm.android.utils.thread; import android.app.Activity; import android.content.Context; import android.widget.Toast; public class ThreadUtils { public static Object context = null; private static Activity activity; /** * setCurrentActivity(this) in onStart() on each activity * setCurrentActivity(this) in onResume() on each activity * setCurrentActivity(null) in onPause() on each activity */ public static void setCurrentActivity(Activity currentActivity) { activity = currentActivity; } public static Activity currentActivity() { return activity; } public static void message(final String message) { activity.runOnUiThread(new Runnable() { public void run() { Toast.makeText((Context) context, message, Toast.LENGTH_SHORT).show(); } }); } }
Example Usage
@Override protected void onStart() { super.onStart(); ThreadUtils.setCurrentActivity(this); ThreadUtils.context = getBaseContext(); } ThreadUtils.message("A message from thread, will normally fail!!!");
Saturday, April 27, 2013
Android custom dialog example
In this tutorial, we show you how to create a custom dialog in Android. See following steps :
File : res/layout/main.xml
File : res/layout/login.xml
Read the comment and demo in next step, it should be self-explorary.
- Create a custom dialog layout (XML file).
- Attach the layout to
Dialog
. - Display the
Dialog
. - Done.
1 Android Layout Files
Two XML files, one for main screen, one for custom dialog.File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btnLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Login Dialog" /> </LinearLayout>
<?xml version="1.0" encoding="UTF-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/sldjfsjdflsdf" android:textAppearance="?android:attr/textAppearanceLarge" /> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView1" android:layout_width="45dp" android:layout_height="45dp" android:src="@drawable/user" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <requestFocus /> </EditText> </LinearLayout> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView2" android:layout_width="45dp" android:layout_height="45dp" android:src="@drawable/password" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:inputType="textPassword" /> </LinearLayout> <Button android:id="@+id/btnLoginPrompt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/login" /> </TableLayout>
Button btnLogin = (Button)findViewById(R.id.btnLogin); btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { final Dialog dialog = new Dialog(ContactspaceandroidActivity.this); dialog.setContentView(R.layout.login); dialog.setTitle("Title..."); dialog.show(); Button azxc = (Button) dialog.findViewById(R.id.btnLoginPrompt); azxc.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { System.out.println("BTN LOGIN CLICKED."); EditText txtUserName = (EditText) dialog.findViewById(R.id.txtUserName); EditText txtPassword = (EditText) dialog.findViewById(R.id.txtPassword); if(txtUserName.getText().length() <= 0) { Toast.makeText(ContactspaceandroidActivity.this, "Enter username.", Toast.LENGTH_LONG).show(); return; } if(txtPassword.getText().length() <= 0) { Toast.makeText(ContactspaceandroidActivity.this, "Enter password.", Toast.LENGTH_LONG).show(); return; } } }); } });
Friday, April 26, 2013
Android, show list of items and bind click on list items
Call list item intent from your application class:
Intent intent = new Intent(MyFirstAppActivity.this, LentList.class);
startActivity(intent);
Here, MyFirstAppActivity is the main class and LentList is the class where list items would show.
First, create a layout file under layout folder, such named list.xml and paste the following content:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" />
</LinearLayout>
Now create LentIist.java class:
public class LentList extends ListActivity
private ArrayList<LentPerson> liLentPerson;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
this.generateLentPersons();
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, liLentPerson.toArray()));
}
Function: generateLentPersons() is as following:
Function MyAdapter is as following:
Intent intent = new Intent(MyFirstAppActivity.this, LentList.class);
startActivity(intent);
Here, MyFirstAppActivity is the main class and LentList is the class where list items would show.
First, create a layout file under layout folder, such named list.xml and paste the following content:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" />
</LinearLayout>
Now create LentIist.java class:
public class LentList extends ListActivity
private ArrayList<LentPerson> liLentPerson;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
this.generateLentPersons();
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, liLentPerson.toArray()));
}
Function: generateLentPersons() is as following:
private ArrayList<Person> getPersons() { ArrayList<Person> liPerson = new ArrayList<Person>(); person = new Person(1, "Pritom Kumar", "Software Engineer", "KU"); return liPerson; }
private class MyAdapter extends ArrayAdapter<Object> { public MyAdapter(Context context, int resource, Object[] persons) { super(context, resource, persons); } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = inflater.inflate(R.layout.list_each, parent, false); LentPerson p = (Person) getItem(position); TextView textView1 = (TextView) row.findViewById(R.id.textView1); TextView textView2 = (TextView) row.findViewById(R.id.textView2); TextView textView3 = (TextView) row.findViewById(R.id.textView3); textView1.setText(p.getName()); /* Pritom Kumar */ textView2.setText(p.getDesignation()); /* Software Engineer */ textView3.setText(p.getUniversity()); /* KU */ /* Bind event on row click */ row.setOnClickListener(new OnItemClickListener(p)); return row; } }
Layout file list_each.xml as following:
<?xml version="1.0" encoding="UTF-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Small Text" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Small Text" android:textAppearance="?android:attr/textAppearanceSmall" /> </TableLayout>
private class OnItemClickListener implements OnClickListener{ private LentPerson p; public OnItemClickListener(LentPerson p) { this.p = p; } public void onClick(View arg0) { Toast.makeText(LentList.this, p.getName(), Toast.LENGTH_SHORT).show(); Intent intent = new Intent(LentList.this, PersonDetails.class); intent.putExtra("personId", p.getId()); intent.putExtra("txtName", p.getName()); intent.putExtra("txtBorrower", p.getborrower()); intent.putExtra("txtCategory", p.getCategory()); startActivity(intent); } }
Java class PersonDetails is as following:
package com.pkm.andrd; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class PersonDetails extends Activity { private TextView textView2; private TextView textView4; private TextView textView6; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.persondetails); textView2 = (TextView) findViewById(R.id.textView2); textView4 = (TextView) findViewById(R.id.textView4); textView6 = (TextView) findViewById(R.id.textView6); textView2.setText(getIntent().getExtras().getString("txtName")); textView4.setText(getIntent().getExtras().getString("txtBorrower")); textView6.setText(getIntent().getExtras().getString("txtCategory")); } }Layout R.layout.persondetails is as following:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textView7" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/s2610132158" android:textAppearance="?android:attr/textAppearanceLarge" /> <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/textView1" android:layout_width="90dp" android:layout_height="wrap_content" android:text="@string/Name" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> </TableRow> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/textView3" android:layout_width="90dp" android:layout_height="wrap_content" android:text="@string/borrower" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <LinearLayout android:id="@+id/linearLayout3" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/textView5" android:layout_width="90dp" android:layout_height="wrap_content" android:text="@string/category" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> </LinearLayout>
Make sure you have the following entry in your manifest file under application tag:
<activity android:name=".LentList" />
<activity android:name=".PersonDetails" />
how to make second layout xml file in android with graphical tab
Make sure you open the layout XML in Eclipse using the "Android Layout
Editor": right-click (or if on a Mac, ctrl-click) the layout file, then
select "Open With..." and "Android Layout Editor".
Pass arguments or data from one activity class to another activity class android
Suppose you are in activity class `First` that take some input such as your name and roll number and type of student.
Now you want to show them in another activity class `Second`.
First get name and roll number and type of student from text box and.
EditText txtName = (EditText) findViewById(R.id.txtName);
EditText txtRoll = (EditText) findViewById(R.id.txtRoll);
Spinner m_myDynamicSpinner;
ArrayAdapter<CharSequence> m_adapterForSpinner;
m_myDynamicSpinner = (Spinner) findViewById(R.id.dynamicSpinner);
m_adapterForSpinner = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.add("Student");
m_adapterForSpinner.add("Ex-student");
m_adapterForSpinner.add("Employee");
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
Now call `Second` activity by this way:
Intent intent = new Intent(First.this, Second.class);
intent.putExtra("txtName", txtName.getText().toString());
intent.putExtra("txtRoll", txtRoll.getText().toString());
intent.putExtra("txtStudentType", m_myDynamicSpinner.getSelectedItem().toString());
startActivity(intent);
And get the values from `Second` activity class by:
getIntent().getExtras().getString("txtName");
getIntent().getExtras().getString("txtRoll");
getIntent().getExtras().getString("txtStudentType");
Now you want to show them in another activity class `Second`.
First get name and roll number and type of student from text box and.
EditText txtName = (EditText) findViewById(R.id.txtName);
EditText txtRoll = (EditText) findViewById(R.id.txtRoll);
Spinner m_myDynamicSpinner;
ArrayAdapter<CharSequence> m_adapterForSpinner;
m_myDynamicSpinner = (Spinner) findViewById(R.id.dynamicSpinner);
m_adapterForSpinner = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.add("Student");
m_adapterForSpinner.add("Ex-student");
m_adapterForSpinner.add("Employee");
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
Now call `Second` activity by this way:
Intent intent = new Intent(First.this, Second.class);
intent.putExtra("txtName", txtName.getText().toString());
intent.putExtra("txtRoll", txtRoll.getText().toString());
intent.putExtra("txtStudentType", m_myDynamicSpinner.getSelectedItem().toString());
startActivity(intent);
And get the values from `Second` activity class by:
getIntent().getExtras().getString("txtName");
getIntent().getExtras().getString("txtRoll");
getIntent().getExtras().getString("txtStudentType");
Android Writing your own Content provider
You start by sub-classing ContentProvider. Since
Implementing a content provider involves always the following steps:
That’s why I used the following line in the code sample above:
<provider
android:name="pritom.kumar.content.provider.LentItemsProvider"
android:authorities="pritom.kumar.content.provider"
android:grantUriPermissions="true"/>
Your own content provider class should look like this:
Your DataHandler class should look like this:
ContentProvider
is an abstract class you have to implement the five abstract methods.
These methods are explained in detail later on, for now simply use the
stubs created by Eclipse (or whatever tool you use).Implementing a content provider involves always the following steps:
- Create a class that extends
ContentProvider
- Define the authority
- Define the URI or URIs
- Create constants to ease client-development
- Implement the
getType()
method - Implement the CRUD-methods
- Add the content provider to your
AndroidManifest.xml
Method | Usage |
---|---|
getType(Uri) | Returns the MIME type for this URI |
delete(Uri uri, String selection, String[] selectionArgs) | Deletes records |
insert(Uri uri, ContentValues values) | Adds records |
query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) | Return records based on selection criteria |
update(Uri uri, ContentValues values, String selection, String[] selectionArgs) | Modifies data |
Notifying listeners of dataset changes
Clients often want to be notified about changes in the underlying datastore of your content provider. So inserting data, as well as deleting or updating data should trigger this notification.That’s why I used the following line in the code sample above:
| getContext().getContentResolver().notifyChange(uri, null ); |
Configuring your content provider
As with any component in Android you also have to register your content provider within theAndroidManifest.xml
file. The next code sample shows a typical example configuration for a content provider.<provider
android:name="pritom.kumar.content.provider.LentItemsProvider"
android:authorities="pritom.kumar.content.provider"
android:grantUriPermissions="true"/>
Your own content provider class should look like this:
package pritom.kumar.content.provider; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.provider.BaseColumns; import android.text.TextUtils; import android.net.Uri; public class LentItemsProvider extends ContentProvider { private SQLiteDatabase db; private DataHandler dataHandler; // public constants for client development public static final String AUTHORITY = "pritom.kumar.content.provider"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + LentItems.CONTENT_PATH); // helper constants for use with the UriMatcher private static final int LENTITEM_LIST = 1; private static final int LENTITEM_ID = 2; private static final UriMatcher URI_MATCHER; public static interface LentItems extends BaseColumns { public static final String DATABASE_NAME = "reminders.db"; public static final String DATABASE_TABLE_NAME = "reminders"; public static final int DATABASE_VERSION = 1; public static final Uri CONTENT_URI = LentItemsProvider.CONTENT_URI; public static final String NAME = "name"; public static final String CATEGORY = "category"; public static final String BORROWER = "borrower"; public static final String CONTENT_PATH = "items"; public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/LentItemsProvider"; public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/LentItemsProvider"; public static final String[] PROJECTION_ALL = {_ID, NAME, CATEGORY, BORROWER}; public static final String SORT_ORDER_DEFAULT = NAME + " ASC"; } // prepare the UriMatcher static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(AUTHORITY, LentItems.CONTENT_PATH, LENTITEM_LIST); URI_MATCHER.addURI(AUTHORITY, LentItems.CONTENT_PATH + "/#", LENTITEM_ID); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int delCount = 0; switch (URI_MATCHER.match(uri)) { case LENTITEM_LIST: delCount = db.delete(DataHandler.TBL_ITEMS, selection, selectionArgs); break; case LENTITEM_ID: String idStr = uri.getLastPathSegment(); String where = LentItems._ID + " = " + idStr; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } delCount = db.delete(DataHandler.TBL_ITEMS, where, selectionArgs); break; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } // notify all listeners of changes: if (delCount > 0) { getContext().getContentResolver().notifyChange(uri, null); } return delCount; } @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case LENTITEM_LIST: return LentItems.CONTENT_TYPE; case LENTITEM_ID: return LentItems.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { if (URI_MATCHER.match(uri) != LENTITEM_LIST) { throw new IllegalArgumentException("Unsupported URI for insertion: " + uri); } if(db == null) { System.out.println(" DB NULL "); } System.out.println(values.size()); long id = db.insert(DataHandler.TBL_ITEMS, null, values); if (id > 0) { // notify all listeners of changes and return itemUri: Uri itemUri = ContentUris.withAppendedId(uri, id); getContext().getContentResolver().notifyChange(itemUri, null); return itemUri; } // s.th. went wrong: throw new SQLException("Problem while inserting into " + DataHandler.TBL_ITEMS + ", uri: " + uri); // use another exception here!!! } @Override public boolean onCreate() { dataHandler = new DataHandler(getContext()); db = dataHandler.getWritableDatabase(); System.out.println("LentItemsProivider onCreate done. Data base is "+(db==null?"null":"not null")+"."); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); builder.setTables(DataHandler.TBL_ITEMS); if (TextUtils.isEmpty(sortOrder)) { sortOrder = LentItems.SORT_ORDER_DEFAULT; } System.out.println("HERE IN query matcher: "+URI_MATCHER.match(uri)); switch (URI_MATCHER.match(uri)) { case LENTITEM_LIST: // all nice and well break; case LENTITEM_ID: // limit query to one row at most: builder.appendWhere(LentItems._ID + " = " + uri.getLastPathSegment()); break; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } Cursor cursor = builder.query(db, projection, selection, selectionArgs, null, null, sortOrder); // if we want to be notified of any changes: cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int updateCount = 0; switch (URI_MATCHER.match(uri)) { case LENTITEM_LIST: updateCount = db.update(DataHandler.TBL_ITEMS, values, selection, selectionArgs); break; case LENTITEM_ID: String idStr = uri.getLastPathSegment(); String where = LentItems._ID + " = " + idStr; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } updateCount = db.update(DataHandler.TBL_ITEMS, values, where, selectionArgs); break; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } // notify all listeners of changes: if (updateCount > 0) { getContext().getContentResolver().notifyChange(uri, null); } return updateCount; } }
package pritom.kumar.content.provider; import pritom.kumar.content.provider.LentItemsProvider.LentItems; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DataHandler extends SQLiteOpenHelper { private String DATABASE_CREATE_SCHEMA = "create table " + LentItems.DATABASE_TABLE_NAME + " (" + LentItems._ID + " integer primary key autoincrement, " + LentItems.NAME + " text not null, " + LentItems.CATEGORY + " text not null, " + LentItems.BORROWER+" text not null );"; public DataHandler(Context context) { super(context, LentItems.DATABASE_NAME, null, LentItems.DATABASE_VERSION); } public static final String DEFAULT_TBL_ITEMS_SORT_ORDER = "ASC"; private SQLiteDatabase db; public static final String TBL_ITEMS = LentItems.DATABASE_TABLE_NAME; @Override public void onCreate(SQLiteDatabase arg0) { if(arg0 == null) { System.out.println("Database is null on create."); } else { System.out.println("Database is not null on create."); } db = arg0; db.execSQL(DATABASE_CREATE_SCHEMA); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } }
Use your own custom provider by this code follow:
<?php
Bind your content provider on create, update and delete mode.
Follow the link for details.
getContentResolver().registerContentObserver(LentItems.CONTENT_URI, true, new MyObserver(null));
/* Get your ContentResolver class */
ContentResolver resolver = getContentResolver();
/* Create content values to insert */
ContentValues values = new ContentValues(); values.put(LentItems.NAME, "Software Engineer Basic"); values.put(LentItems.BORROWER, "Pritom Kumar"); values.put(LentItems.CATEGORY, "Computer Science And Engineering"); System.out.println("Row insert id: "+resolver.insert(LentItems.CONTENT_URI, values)); /* Get All data from content provider */ String[] PROJECTION=new String[] { LentItems.BORROWER, LentItems.NAME, LentItems.CATEGORY, LentItems._ID }; Cursor c = resolver.query(LentItemsProvider.CONTENT_URI, PROJECTION, null, null, null); if (c == null){ System.out.println("NULL"); } else{ while (c.moveToNext()) { String s1 = c.getString(c.getColumnIndex(LentItems._ID)); String s2 = c.getString(c.getColumnIndex(LentItems.NAME)); String s3 = c.getString(c.getColumnIndex(LentItems.CATEGORY)); String s4 = c.getString(c.getColumnIndex(LentItems.BORROWER)); System.out.println(s1+", "+s2+", "+s3+", "+s4); } } ?>
Subscribe to:
Posts (Atom)