Load Webview in second Fragment when Button is clicked from First Fragment - eclipse

I have two Fragments. First Fragment is named as Fragment1 and Second Fragment named as physics. First Fragment have Two Buttons. I would Like to show a local html page ( say A.html when Button1 is pressed and B.html when Button2 is Pressed ) in Second Fragment i.e in physics.java
My Fragment.java contains following code
package com.nepalpolice.mnemonics;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by Sagar on 2017/09/23.
*/
public class Fragment1 extends Fragment implements View.OnClickListener{
public Button button;
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
button = (Button) view.findViewById(R.id.button1);
button = (Button) view.findViewById(R.id.button2);
return view;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), physics.class);
switch (v.getId()) {
case R.id.button1:
intent.putExtra("url", "file:///android_asset/B.html");
startActivity(intent);
break;
case R.id.button2:
intent.putExtra("url", "file:///android_asset/A.html");
startActivity(intent);
break;
default:
break;
}
}
}
and My SecondFragment contains following code
package com.nepalpolice.mnemonics;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Created by Sagar on 2017/09/23.
*/
public class physics extends Fragment {
WebView myWebView;
public physics() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_fragment2, container, false);
String url = getActivity().getIntent().getStringExtra("url");
myWebView=(WebView)rootView.findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl(url);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
return rootView;
}
}
and main fragment_fragment1.xml contains
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nepalpolice.mnemonics.Fragment1">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:text="button01"
android:onClick="onClick"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:text="button02"
android:onClick="onClick"/>
</LinearLayout>
</FrameLayout>
and Secondfragment.xml has
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
But my is Crashing with following Error.
java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button1'
I'm almost Done with my project. If it could be done...It would mean a lot for me.

Related

Displaying Navigation drawer in all activities problem

I'm making a navigation drawer with different activities and i want to display the same navigation drawer in all activities , i take the same code and put it in all activities but when i click on the activities my app crashes all the time i don't know why
Try below code for displaying Navigation drawer on all activity, hope this example help...!
BaseActivity
public class BaseActivity extends AppCompatActivity {
ArrayList<String> menuList;
protected FrameLayout frameLayout;
protected ListView mDrawerList;
protected static int position;
private static boolean isLaunch = true;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
#SuppressLint("ResourceAsColor")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.navigation_drawer_base_layout);
prepareListItems();
frameLayout = findViewById(R.id.content_frame);
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerList = findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.header, null);
mDrawerList.addHeaderView(header);
mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, menuList));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
openActivity(position);
}
});
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.menu);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.mipmap.ic_launcher_round, /* nav drawer image to replace 'Up' caret */
R.string.open_drawer, /* "open drawer" description for accessibility */
R.string.close_drawer) /* "close drawer" description for accessibility */ {
#Override
public void onDrawerClosed(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
Objects.requireNonNull(getSupportActionBar()).setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
if (isLaunch) {
isLaunch = false;
openActivity(1);
}
}
private void prepareListItems() {
menuList = new ArrayList<>();
menuList.add(" Activity1 ");
menuList.add(" Activity2 ");
menuList.add(" Activity3 ");
menuList.add(" Activity4 ");
}
/**
* #param position Launching activity when any list item is clicked.
*/
protected void openActivity(int position) {
mDrawerList.setItemChecked(position - 1, true);
mDrawerLayout.closeDrawer(mDrawerList);
BaseActivity.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
break;
case 1:
startActivity(new Intent(this, Activity1.class));
break;
case 2:
startActivity(new Intent(this, Activity2.class));
break;
case 3:
startActivity(new Intent(this, Activity3.class));
break;
case 4:
startActivity(new Intent(this, Activity4.class));
break;
default:
break;
}
// Toast.makeText(this, "Selected Item Position::" + position, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
}
Activity1
public class Activity1 extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_main, frameLayout);
mDrawerList.setItemChecked(position, true);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
navigation_drawer_base_layout
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/simple_brushed_metal"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</androidx.drawerlayout.widget.DrawerLayout>
header
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/shade">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="serif"
android:gravity="center"
android:text="#string/app_name"
android:textColor="#color/textColorPrimary"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/developed_by_nd_software_solution"
android:textColor="#color/textColorPrimary"
android:textSize="12sp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="8dp"
android:background="#color/textColorPrimary" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
drawer_list_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/activatedBackgroundIndicator"
android:fontFamily="serif"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/textColorPrimary" />
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="serif"
android:gravity="center"
android:text="#string/app_name"
android:textColor="#color/textColorPrimary"
android:textSize="18sp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here I have provided code for one activity (Activity1), write code for other activities like Activity2, Activity3 etc.

How to change widget view in background service

I have created widget. I am trying to update the widget in background each 5 seconds (For testing purpose 5 second). But it is not getting update.Is any mistake on my code.
Provider class
package com.widget.widgetapplication;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.util.Random;
public class MyWidget extends AppWidgetProvider {
private int randomNumber = 0;
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Toast.makeText(context, "Receive", Toast.LENGTH_SHORT).show();
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
Toast.makeText(context, "Update", Toast.LENGTH_SHORT).show();
// Get all ids
ComponentName thisWidget = new ComponentName(context,
MyWidget.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
// create some random data
randomNumber = new Random().nextInt(100);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
Log.w("WidgetExample", String.valueOf(randomNumber));
// Set the text
remoteViews.setTextViewText(R.id.time, String.valueOf(randomNumber));
appWidgetManager.notifyAppWidgetViewDataChanged(widgetId, R.id.time);
// Register an onClickListener
Intent intent = new Intent(context, MyWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.watch, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}
widget info xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minHeight="100dp"
android:minWidth="100dp"
android:previewImage="#drawable/analog_watch"
android:initialLayout="#layout/widget_layout"
android:updatePeriodMillis="5000">
</appwidget-provide
Registered receiver in manifest
<receiver android:name=".MyWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="#xml/widget_info"/>
</receiver>
Widget layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent">
<AnalogClock
android:id="#+id/watch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"
android:textStyle="bold"
android:text="Time is : "
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"/>
</LinearLayout>
YES. you are doing it wrong.
the minimum available value for updatePeriodMillis is 30min (1800000 millis).
official document :
Note: Updates requested with updatePeriodMillis will not be delivered more than once every 30 minutes.

Display two webview in one screen

i'm trying to make a webview app which can display two website in one screen. but when i run my app it display one website and open on new browser. how can i display two website and it doesn't work on new browser?
this is my WebViewActivity class:
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebViewActivity extends Activity {
private WebView webView1, webView2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView1 = (WebView) findViewById(R.id.webView1);
webView1.getSettings().setJavaScriptEnabled(true);
webView1.loadUrl("http://www.google.com");
webView2 = (WebView) findViewById(R.id.webView2);
webView2.getSettings().setJavaScriptEnabled(true);
webView2.loadUrl("http://www.google.com");
}
}
this is my xml file:
<?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" >
<WebView
android:id="#+id/webview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.39" />
<WebView
android:id="#+id/webview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.53" />
</LinearLayout>
I suggest you use framelayout and try to set webviewClient to your webview
this function shouldOverrideUrlLoading (in the declaration of the webviewClient)
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
Log.i("Page", url);
view.setWebViewClient(new MyWebViewClient());
view.setWebChromeClient(new MyWebChromeClient());
view.loadUrl(url);
return true;
}
will override url loaded by the webview and force it to be loaded in the webview not in the new browser

Progress bar isn't working

I am new to android ,I want make an app which needs a progress bar, but the code which I wrote seems to crash each time I run it .As till now I am unable to find the bug.I am using a vertical progress bar.
thanx in advance.
package com.example.progtask;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends Activity implements OnClickListener, Runnable {
private ProgressBar pb;
private Button show;
private Button hide;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
show = (Button) findViewById(R.id.button1);
hide = (Button) findViewById(R.id.hide);
// pb.setVisibility(ProgressBar.GONE);
show.setOnClickListener(this);
hide.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(show)) {
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(12);
new Thread(this).start();
} else {
pb.setVisibility(ProgressBar.GONE);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
while (n < 10) {
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pb.setProgress(n);
}
}
Below is the Xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="picelate"
tools:context=".MainActivity" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="82dp"
android:layout_toLeftOf="#+id/textView1"
android:text="show" />
<Button
android:id="#+id/hide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/textView1"
android:text="hide" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentLeft="true" />
</RelativeLayout>
Try this
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button1:
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(12);
new Thread(this).start();
break;
case R.id.hide:
// do the needful.
break;
}
}
This is how it worked:
public class MainActivity extends Activity implements OnClickListener, Runnable {
private ProgressBar pb;
private Button show;
private Button hide;
int n;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
show = (Button) findViewById(R.id.button1);
hide = (Button) findViewById(R.id.button2);
// pb.setVisibility(ProgressBar.GONE);
show.setOnClickListener(this);
hide.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.button1:
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(100);
n = 0;
new Thread(this).start();
break;
case R.id.button2:
// do the needful.
pb.setVisibility(ProgressBar.GONE);
break;
}
}
#Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
while (n < 100) {
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}pb.setProgress(n*10);
}
pb.setProgress(n*10);
}
}
the xml file is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hide" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progressDrawable="#drawable/progbar"
android:layout_gravity="bottom"
/>
</LinearLayout>

pass values of clicked item in item list to a new activity

I am trying to get the values clicked on my listactivity to display on the third.xml. it has 4 editText fields. I want to display the 4 columns on the 4 ET fields. HELP!!!
HEre is a code for getting a specific record in my DBAdapter:
public Cursor getRecord(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {ROW_ID,
KEY_FIRSTNAME, KEY_LASTNAME, KEY_CITY, KEY_STATE},
ROW_ID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Then here is my Second.java list acitivity
package com.dtan.testcontacts;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class Second extends ListActivity {
public final static String ID_EXTRA="com.dtan.testcontacts._ID";
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db.open();
Cursor c = db.getAllContacts();
ArrayList<String> columns = new ArrayList<String>();
int iFirstName = c.getColumnIndex(DBAdapter.KEY_FIRSTNAME);
int iLastName = c.getColumnIndex(DBAdapter.KEY_LASTNAME);
for(c.move(0); c.moveToNext(); c.isAfterLast()){
String columnstring = c.getString(iFirstName)+ " " + c.getString(iLastName)+"\n";
columns.add(columnstring);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, columns);
setListAdapter(adapter);
final ListView lv = getListView();
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextmenu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()){
case R.id.delete:
AlertDialog.Builder abuilder = new AlertDialog.Builder(Second.this);
abuilder.setMessage("Are you sure you want to delete?");
abuilder.setCancelable(false);
abuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Cursor c = db.getAllContacts();
c.moveToPosition(info.position);
String id = c.getString(c.getColumnIndex(DBAdapter.ROW_ID));
db.open();
db.deleteContact(Long.parseLong(id));
c.close();
Toast toast = Toast.makeText(Second.this, "Contact Deleted Successfully", 5000);
toast.show();
Intent i = new Intent(Second.this, Second.class);
startActivity(i);
}
});
abuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = abuilder.create();
alert.show();
return true;
case R.id.edit:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> lv, View cell,
int position, long id) {
Intent i = new Intent(Second.this, Third.class);
i.putExtra("entry_id", position);
startActivity(i);
}
});
}
return super.onContextItemSelected(item);
}
}
Finally, here is the Third activity where i want to display the value clicked on the listactivity to display on each edittext. xml first then java code:
<EditText
android:id="#+id/editText1Third"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:clickable="false"
android:ems="10"
android:hint="Firstname"
android:inputType="text"
android:text="#string/none" />
<TextView
android:id="#+id/textView1"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:text="#string/fname" />
<EditText
android:id="#+id/editText2Third"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="Lastname"
android:inputType="text"
android:text="#string/none" />
<TextView
android:id="#+id/textView2"
android:layout_width="74dp"
android:layout_height="wrap_content"
android:text="#string/lastname" />
<EditText
android:id="#+id/editText3Third"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="City"
android:inputType="text"
android:text="#string/none" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/city" />
<EditText
android:id="#+id/editText4Third"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="State"
android:inputType="text"
android:text="#string/none" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/state" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="64dp" >
<Button
android:id="#+id/ButtonUpdateThird"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:text="#string/update" />
</RelativeLayout>
</LinearLayout>
Third.java
package com.dtan.testcontacts;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.EditText;
public class Third extends Activity {
private DBAdapter db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
int b = this.getIntent().getExtras().getInt("entry_id");
EditText firstname = (EditText) findViewById(R.id.editText1Third);
db.open();
Cursor c = db.getRecord(b);
firstname.setText(c.getString(1));
db.close();
}
}