I am currently learning about widgets in Android.
I want to be able to update my textview, but each time when I try to update it - my program crashes.
Here is my class:
public class DayWidget extends AppWidgetProvider {
public static CheckDate CheckDate;
public static EventList EventList;
public static String EVENT_CLICK = "EventClick";
public String msg;
public RemoteViews views;
public AppWidgetManager manager;
public Context cntxt;
public Intent intnt;
public int[] ids;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
super.onUpdate(context, appWidgetManager, appWidgetIds);
CheckDate = new CheckDate();
EventList = new EventList();
manager = appWidgetManager;
views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
ids = appWidgetIds;
Intent intent = new Intent(context, DayWidget.class);
intent.setAction(EVENT_CLICK);
intent.putExtra("msg", "change");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.Event, actionPendingIntent);
CheckDate.Check();
views.setTextViewText(R.id.Today, CheckDate.Today);
manager.updateAppWidget(ids, views);
}
public void UpdateWidget(){
Bundle extras = intnt.getExtras();
if(extras!=null) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(cntxt);
ComponentName AppWidget = new ComponentName(cntxt.getPackageName(), DayWidget.class.getName());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(AppWidget);
views.setTextViewText(R.id.Event, "New text");
onUpdate(cntxt, appWidgetManager, appWidgetIds);
}
}
public void onReceive(Context context, Intent intent){
intnt = intent;
cntxt = context;
if(EVENT_CLICK.equals(intent.getAction())){
try{
msg = intent.getStringExtra("msg");
}catch(NullPointerException e){
e.printStackTrace();
}
UpdateWidget();
//Toast toast = Toast.makeText(cntxt, "TEST", Toast.LENGTH_LONG);
//toast.show();
}
super.onReceive(context, intent);
}
}`
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sunmille.day"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver
android:name="DayWidget">
<intent-filter>
<action
android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action
android:name="android.appwidget.action.ACTION_WIDGET_RECEIVER" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_data" />
</receiver>
</application>
Widget data
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="294dp"
android:minHeight="72dp"
android:minResizeWidth="294dp"
android:minResizeHeight="72dp"
android:updatePeriodMillis="0"
android:resizeMode="horizontal|vertical"
android:initialLayout="#layout/widget_layout">
Widget layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/widget_background" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<TextView
android:id="#+id/TopText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cегодня "
android:textIsSelectable="false"
android:textColor="#000000"
android:textSize="20sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/Today"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="false"
android:textColor="#000000"
android:textSize="20sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<TextView
android:id="#+id/Event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="false"
android:textColor="#000000"
android:textSize="20sp"
android:text="Some event"
android:textAppearance="?android:attr/textAppearanceLarge" />
Log:
03-29 14:10:15.954: E/AndroidRuntime(4552): java.lang.RuntimeException: Unable to start receiver com.sunmille.day.DayWidget: java.lang.NullPointerException
03-29 14:10:15.954: E/AndroidRuntime(4552): at com.sunmille.day.DayWidget.UpdateWidget(DayWidget.java:61)
03-29 14:10:15.954: E/AndroidRuntime(4552): at com.sunmille.day.DayWidget.onReceive(DayWidget.java:77)
CORRECT CODE:
public class DayWidget extends AppWidgetProvider {
public static CheckDate CheckDate;
public static EventList EventList;
public static String EVENT_CLICK = "EventClick";
public String msg;
public RemoteViews rviews;
public AppWidgetManager manager;
public Context cntxt;
public Intent intnt;
public int[] ids;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
super.onUpdate(context, appWidgetManager, appWidgetIds);
CheckDate = new CheckDate();
EventList = new EventList();
manager = appWidgetManager;
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
ids = appWidgetIds;
Intent intent = new Intent(context, DayWidget.class);
intent.setAction(EVENT_CLICK);
intent.putExtra("msg", "change");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.Event, actionPendingIntent);
CheckDate.Check();
views.setTextViewText(R.id.Today, CheckDate.Today);
manager.updateAppWidget(ids, views);
}
public void UpdateWidget(){
Bundle extras = intnt.getExtras();
if(extras!=null) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(cntxt);
ComponentName AppWidget = new ComponentName(cntxt.getPackageName(), DayWidget.class.getName());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(AppWidget);
rviews = new RemoteViews(AppWidget.getPackageName(), R.layout.widget_layout);
rviews.setTextViewText(R.id.Event, "New text");
appWidgetManager.updateAppWidget(appWidgetIds, rviews);
}
}
public void onReceive(Context context, Intent intent){
intnt = intent;
cntxt = context;
if(EVENT_CLICK.equals(intent.getAction())){
try{
msg = intent.getStringExtra("msg");
}catch(NullPointerException e){
e.printStackTrace();
}
UpdateWidget();
Toast toast = Toast.makeText(cntxt, "TEST", Toast.LENGTH_LONG);
toast.show();
}
super.onReceive(context, intent);
}
}
Variable views of type RemoteViews is null. You can see it on Logcat output.
Related
I am trying to update my widget's TextView Text from a BroadcastReceiver on ClickPendingIntent. I am not having much luck. Can I please get some help with this? In my ActionReceiver.class which extends BroadcastReceiver, I know that I need to update the widget after changing the textview text. I am not sure how to do that. Unfortunately, I can't use statics without crashing the app and widget. Here is my code...
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mywidget">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<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/my_widget_info" />
</receiver>
<activity
android:name=".MainActivity"
android:screenOrientation="locked">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ActionReceiver"/>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<TextView
android:id="#+id/myTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAlignment="center"
android:text="#string/default_tv_text"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
<EditText
android:id="#+id/myET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/myTV"
android:inputType="text"
android:hint="#string/default_et_text"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#android:color/black"
tools:ignore="Autofill" />
<View
android:id="#+id/myView"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="#id/myET"/>
<Button
android:id="#+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/myView"
android:layout_centerHorizontal="true"
android:text="#string/button_text"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
</RelativeLayout>
my_widget.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp"
android:layout_height="110dp"
android:padding="#dimen/widget_margin">
<TextView
android:id="#+id/appwidget_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="8dp"
android:contentDescription="#string/appwidget_text"
android:text="#string/appwidget_text"
android:textColor="#android:color/white"
android:textSize="24sp"
android:textStyle="bold|italic" />
</RelativeLayout>
strings.xml
<resources>
<string name="app_name">My Widget</string>
<string name="default_tv_text">Hello World!</string>
<string name="default_et_text">Enter Something To Change The Text Above.</string>
<string name="button_text">OK</string>
<string name="appwidget_text">EXAMPLE</string>
<string name="appwidget_text_changed">Hello World!</string>
<string name="add_widget">Add widget</string>
</resources>
MainActivity.class
package com.example.mywidget;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView tv;
EditText et;
Button btn;
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.myTV);
et = findViewById(R.id.myET);
btn = findViewById(R.id.myButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getEditText = et.getText().toString();
if (!getEditText.isEmpty()) {
tv.setText(getEditText);
Toast.makeText(getBaseContext(), "Text Changed!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
MyWidget.class
package com.example.mywidget;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyWidget extends AppWidgetProvider {
public void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.appwidget_text);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
Intent actionIntent = new Intent(context, ActionReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.appwidget_text, pi);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
}
ActionReceiver.class
package com.example.mywidget;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class ActionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
CharSequence getNewText = context.getString(R.string.appwidget_text_changed);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setTextViewText(R.id.appwidget_text, getNewText); // The widget needs to be updated from here with something like this updateAppWidget(context, appWidgetManager, appWidgetId);
Toast.makeText(context, "Widget Updated!", Toast.LENGTH_SHORT);
}
}
My Updated MyWidget.class
public class MyWidget extends AppWidgetProvider {
public void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.appwidget_text);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
Intent actionIntent = new Intent(context, MyWidget.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.appwidget_text, pi);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager appWM = AppWidgetManager.getInstance(context);
ComponentName myWidget = new ComponentName(context, MyWidget.class);
int[] appWIDs = appWM.getAppWidgetIds(myWidget);
CharSequence getNewText = context.getString(R.string.appwidget_text_changed);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setTextViewText(R.id.appwidget_text, getNewText);
if (appWIDs == null && appWIDs.length > 0) {
onUpdate(context, appWM, appWIDs);
Toast.makeText(context, "Widget Updated!", Toast.LENGTH_SHORT).show();
}
}
}
It's still not working for me. When I click the textview on the widget, it just launches the app. I'm trying to get the textview to change the default word "Example" to "Hello World" when the textview is clicked on. I've been trying for hours figuring this out.
This is my first time asking a question on SO.
I want to pass my Calculation object to the widget to be displayed on the home screen. I have the widget to update in my MainActivity.java when I click the calculate button:
I'm using Parceler.
Here is my widget after clicking the Calculate button
And the MainActivity
My issue is that the widget is not displaying the calculation info that was supposedly passed to it from the Provider class. it seems to parcelize correctly in my logs that display the calculation, just that I may be setting the widget view incorrectly to receive the data and display it.
public void saveCalcInfo(View v){
[...]
setWidget(calculation);
}
private void setWidget(Calculation calculationToPassToWidget) {
BullAppWidgetProvider.manualUpdateWidgets(getApplicationContext(), calculationToPassToWidget);
}
All I really need from the widget is to receive the calculation info, and display it.
A nice to have would be upon clicking the button "View", launch the MainActivity and autofill the EditTexts with the displayed information about the calculation
Here's my BullAppWidgetProvider.java
public class BullAppWidgetProvider extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Calculation calculation) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_provider);
if (calculation != null) {
views.setTextViewText(R.id.symbol, calculation.getSymbol());
views.setTextViewText(R.id.shares, String.valueOf(calculation.getShares()));
views.setTextViewText(R.id.buy, String.valueOf(calculation.getBuy()));
views.setTextViewText(R.id.sell, String.valueOf(calculation.getSell()));
views.setTextViewText(R.id.comm, String.valueOf(calculation.getComm()));
}
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.viewCalcBT, pendingIntent);
views.setTextViewText(R.id.widget_app_title, context.getString(R.string.widget_prompt));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
static void manualUpdateWidgets(Context context, Calculation calculation) {
ComponentName componentName = new ComponentName(context, BullAppWidgetProvider.class);
Timber.w("Calculation received in manual Update: %s", calculation.toString());
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = manager.getAppWidgetIds(componentName);
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, manager, appWidgetId, calculation);
Toast.makeText(context, "Widget has updated!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId, null);
}
}
}
If needed, here's the
widget_layout.xml
file for reference
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="#color/primary">
<TextView
android:id="#+id/symbol"
style="#style/AdapterStyle"
android:text="#string/ipl" />
<TextView
android:id="#+id/shares"
style="#style/AdapterStyle"
android:layout_alignParentEnd="true"
android:text="#string/_42" />
<TextView
android:id="#+id/buy"
style="#style/AdapterStyle"
android:layout_below="#id/symbol"
android:text="#string/buy" />
<TextView
android:id="#+id/sell"
style="#style/AdapterStyle"
android:layout_below="#id/buy"
android:text="#string/sell" />
<TextView
android:id="#+id/comm"
style="#style/AdapterStyle"
android:layout_below="#id/shares"
android:layout_alignParentEnd="true"
android:text="#string/comm" />
<Button
android:id="#+id/viewCalcBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/sell"
android:layout_alignParentEnd="true"
android:text="#string/view" />
</RelativeLayout>
as well as the
widget_provider.xml
<?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"
android:padding="8dp">
<TextView
android:id="#+id/widget_app_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/app_name" />
<
android:id="#+id/ll_parent_for_widget"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Thank you for your time!
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I can not understand why my application does not open a new activity on a button click.I have a button in my layout file(id is showButton),I need to open another activity when I click on that button.But it does not work and my application will crash.therefore I added a try catch block and get the android monitor result as following.
activity_place_picker.xml
<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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".PlacePickerActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch Places API Picker"
android:id="#+id/pickerButton"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Place Holder"
android:id="#+id/saveButton"
android:layout_below="#+id/pickerButton"
android:layout_centerHorizontal="true"
android:visibility="gone"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Place Holder"
android:id="#+id/showButton"
android:layout_below="#+id/saveButton"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/poweredBy"
android:src="#drawable/powered_by_google_light"/>
This is Place picker class where I have included the onClick listner to the button to open a new activity.
PlacePickerActivity
public class PlacePickerActivity extends AppCompatActivity {
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_picker);
mName = (TextView) findViewById(R.id.textView);
mAddress = (TextView) findViewById(R.id.textView2);
mAttributions = (TextView) findViewById(R.id.textView3);
Button showButton = (Button) findViewById(R.id.showButton);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
pickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(PlacePickerActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Intent i = new Intent(ctx, PlacesActivity.class);
ctx.startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
//Extracting place information from the API
final Place place = PlacePicker.getPlace(this, data);
final String place_Id = place.getId().toString();
final String place_Name = place.getName().toString();
final String place_Address = place.getAddress().toString();
final String place_PhoneNumber = place.getPhoneNumber().toString();
final String place_Website = place.getWebsiteUri().toString();
//Get rating as a float value and converting to string
final float rating = place.getRating();
final String place_Rating = String.valueOf(rating);
final String place_LatLng = place.getLatLng().toString();
final String function_Save = "save_Place";
final String function_Show = "show_Place";
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
mName.setText(place_Name);
mAddress.setText(place_Address);
mAttributions.setText(Html.fromHtml(attributions));
//Accessing the save button and show button in the view and making it visible after selecting a place
final View save = findViewById(R.id.saveButton);
save.setVisibility(View.VISIBLE);
//Passing the Extracted place details to the background worker class
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
BackgroundWorker backgroundWorker = new BackgroundWorker(PlacePickerActivity.this);
backgroundWorker.execute(function_Save,place_Id,place_Name,place_Address,place_PhoneNumber,place_Website,place_Rating,place_LatLng);
}
});
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
PlacesActivity.java
package com.truiton.placepicker;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class PlacesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
}
}
activity_places.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.truiton.placepicker.PlacesActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello world"
android:id="#+id/textView" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.truiton.placepicker">
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBpIGvJfE8eKhoEFCMqV8NrFkWRjTAnNyQ" />
<activity
android:name=".PlacePickerActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PlacesActivity"></activity>
</application>
</manifest>
Android Monitor result when the button clicks
Android Monitor result
Edited : This is the crash log
Crash log
can anyone help me with this?
Write the class name PlacePickerActivity in the intent, your method should be
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Intent i = new Intent(PlacePickerActivity.this , PlacesActivity.class);
ctx.startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
}
});
I found the answer for the question.
This
link helped me to find the answer for the problem. In PlacePickerActivity I have just declare Context ctx;and it does not contain any primitive value. But I have use the it as an argument to open a new activity which will give me a NullPointerException.So instead of
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, PlacesActivity.class);
ctx.startActivity(i);
}
});
I used
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(PlacePickerActivity.this, PlacesActivity.class);
PlacePickerActivity.this.startActivity(i);
}
});
And this fixed my problem.Thank you for every one.
I've created a widget, and on click an Activity has to be launched, I followed the answer to this question [Clickable widgets in android].
However, on click I am unable to get any response, here is the java code to my widget:
Widget.java
public class Widget extends AppWidgetProvider
{
private static String YOUR_AWESOME_ACTION = "YourAwesomeAction";
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
Intent intent = new Intent(context, HomeTeamSelector.class);
intent.setAction(YOUR_AWESOME_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.widgetLayout, pendingIntent);
}
#Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
if (intent.getAction().equals(YOUR_AWESOME_ACTION))
{
Intent x = new Intent(context,HomeTeamSelector.class);
context.startActivity(x);
}
}
}
This is the code to the xml file:
widget.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/widgetLayout"
android:layout_height="match_parent"
android:transitionGroup="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name_extra"
android:id="#+id/textView"
android:layout_centerInParent="true"
android:textColor="#color/colorPrimary"
android:textSize="30sp" />
</RelativeLayout>
The widget is rendered, however I am unable to get any response on click, what is possibly causing this, and how to fix?
try to add AppWidgetProvider receiver in AndroidMenifest.xml like
<receiver
android:name=".Widget"
android:label="#string/widget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget" />
</receiver>
At the click of a button, I want to start an Intent to take a picture, and then display it in my layout. I am using the following code:
private void takePicture() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(),
"Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, bitmap.getHeight()/2, bitmap.getWidth()/2, false));
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}
The Picture is definitely showing, but when I change the activity and go back to this one, the picture goes away. How do I save it permanently?
Well, you will have to manually save the image either in SQL Lite or SD Card or wherever you want.
See this for storing image in SQLite
See this for storing image in SD Card
Try this as my code is working properly
public class PhotoActivity extends Activity {
/** The Constant PICK_IMAGE. */
private static final int PICK_IMAGE = 0;
/** The Constant PICK_IMAGE_FROM_GALLERY. */
private static final int PICK_IMAGE_FROM_GALLERY = 1;
/** The btn cancel. */
private Button btnPhotoCamera,btnPhotoGallery,btnCancel;
/** The img view. */
private ImageView imgView;
/** The u. */
private Uri u;
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_options);
imgView=(ImageView)findViewById(R.id.imgDisplayImage);
btnPhotoCamera=(Button)findViewById(R.id.btnPhotoCamera);
btnPhotoGallery=(Button)findViewById(R.id.btnPhotoGallery);
btnCancel=(Button)findViewById(R.id.btnCancel);
btnPhotoCamera.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent camera=new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("crop", "true");
File f=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
u = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"myFile.jpg"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, u);
startActivityForResult(camera, PICK_IMAGE);
}
});
btnPhotoGallery.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_FROM_GALLERY);
}
});
btnCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent goStartUp=new Intent(PhotoActivity.this, StartUpActivity.class);
goStartUp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goStartUp);
finish();
}
});
}
/* (non-Javadoc)
* #see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode==RESULT_OK )
{
if(requestCode == PICK_IMAGE) {
InputStream is=null;
try {
is = this.getContentResolver().openInputStream(u);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp=BitmapFactory.decodeStream(is);
imgView.setImageBitmap(bmp);
Log.i("Inside", "PICK_IMAGE");
}
if (requestCode == PICK_IMAGE_FROM_GALLERY) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Log.d("data",filePathColumn[0]);
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imgView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Log.i("Inside", "PICK_IMAGE_FROM_GALLERY");
}
}
}
}
XML File:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0" >
<TextView
android:id="#+id/lblSelectOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:text="#string/two_options"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ff0000" />
<Button
android:id="#+id/btnPhotoCamera"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_below="#+id/lblSelectOptions"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="#string/camera" />
<Button
android:id="#+id/btnPhotoGallery"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_below="#+id/btnPhotoCamera"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="#string/gallery" />
<Button
android:id="#+id/btnCancel"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_below="#+id/btnPhotoGallery"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="#string/cancel" />
<TextView
android:id="#+id/lblDisplayImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnCancel"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="#string/below_this_text_image_will_be_displayed"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textSize="13dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/lblDisplayImage"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:gravity="bottom" >
<!--
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
-->
<ImageView
android:id="#+id/imgDisplayImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/lblDisplayImage"
android:layout_centerInParent="true"
android:contentDescription="#string/area_where_image_is_to_be_displayed" />
<!-- </ScrollView> -->
</RelativeLayout>
</RelativeLayout>
Also Modify the Android Manifest file as per your use with following:
<manifest....
<uses-sdk
android:minSdkVersion="3"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_VIDEO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<application....
..........
</application>
</manifest>