#android #android-widget
#Android #android-виджет
Вопрос:
Мне нужно activity в моем приложении. Одно действие используется для увеличения значения count, а другое действие расширяет AppWidget. Поскольку мне нужно регулярно отображать значение count (целое число) в виджете приложения.
Вот мой код activity.
Smoke_Count.java
package com.example.smokecount;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class Smoke_Count extends Activity implements OnTouchListener{
private Button btn;
private TextView txt;
private static int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smoke__count);
btn=(Button)findViewById(R.id.button1);
txt=(TextView)findViewById(R.id.textView1);
txt.setText(String.valueOf(count));
btn.setOnTouchListener(this);
loadInt();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.smoke__count, menu);
return true;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==MotionEvent.ACTION_UP)
{
loadInt();
saveInt("countValue", count);
count ;
txt.setText(String.valueOf(count));
}
return true;
}
public void saveInt(String key,int count)
{
SharedPreferences share= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor edit= share.edit();
edit.putInt(key, count);
edit.commit();
}
public void loadInt()
{
SharedPreferences share= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int counter=share.getInt("countValue", count);
/*Intent i=new Intent(Smoke_Count.this, Widget.class);
i.putExtra("count", counter);
sendBroadcast(i);*/
txt.setText(String.valueOf(counter));
if(counter>=count)
{
count=counter;
}
}
}
И это моя активность виджета
Widget.java
package com.example.smokecount;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
public class Widget extends AppWidgetProvider{
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
for(int i=0;i<appWidgetIds.length;i )
{
int appWidgetID=appWidgetIds[i];
Intent i1=new Intent(Intent.ACTION_VIEW, null, context, Smoke_Count.class);
PendingIntent pending=PendingIntent.getActivity(context, 0, i1, 0);
RemoteViews views=new RemoteViews(context.getPackageName(), R.layout.activity_widget);
views.setOnClickPendingIntent(R.id.imageButton1, pending);
appWidgetManager.updateAppWidget(appWidgetID, views);
}
}
/*@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
super.onReceive(context, intent);
String action=intent.getAction();
Bundle ext=intent.getExtras();
int scount=ext.getInt("count");
Toast.makeText(context, "" scount, Toast.LENGTH_LONG).show();
}*/
}
Это мой XML-файл виджета
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageButton
android:id="@ id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@ id/txtcount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@ id/imageButton1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="18dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Мне нужно отобразить значение count в виджете.
Это logcat
06-30 18:00:36.950: E/AndroidRuntime(2226): FATAL EXCEPTION: main
06-30 18:00:36.950: E/AndroidRuntime(2226): Process: com.example.smokecount, PID: 2226
06-30 18:00:36.950: E/AndroidRuntime(2226): java.lang.RuntimeException: Unable to start receiver com.example.smokecount.Widget: java.lang.NullPointerException
06-30 18:00:36.950: E/AndroidRuntime(2226): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2407)
06-30 18:00:36.950: E/AndroidRuntime(2226): at android.app.ActivityThread.access$1600(ActivityThread.java:135)
06-30 18:00:36.950: E/AndroidRuntime(2226): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
06-30 18:00:36.950: E/AndroidRuntime(2226): at android.os.Handler.dispatchMessage(Handler.java:102)
06-30 18:00:36.950: E/AndroidRuntime(2226): at android.os.Looper.loop(Looper.java:137)
06-30 18:00:36.950: E/AndroidRuntime(2226): at android.app.ActivityThread.main(ActivityThread.java:4998)
06-30 18:00:36.950: E/AndroidRuntime(2226): at java.lang.reflect.Method.invokeNative(Native Method)
06-30 18:00:36.950: E/AndroidRuntime(2226): at java.lang.reflect.Method.invoke(Method.java:515)
06-30 18:00:36.950: E/AndroidRuntime(2226): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
06-30 18:00:36.950: E/AndroidRuntime(2226): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
06-30 18:00:36.950: E/AndroidRuntime(2226): at dalvik.system.NativeStart.main(Native Method)
06-30 18:00:36.950: E/AndroidRuntime(2226): Caused by: java.lang.NullPointerException
06-30 18:00:36.950: E/AndroidRuntime(2226): at com.example.smokecount.Widget.onReceive(Widget.java:42)
06-30 18:00:36.950: E/AndroidRuntime(2226): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2400)
06-30 18:00:36.950: E/AndroidRuntime(2226): ... 10 more
Комментарии:
1. ответьте мне, сэр @pareshmayani
Ответ №1:
Та область, которая закомментирована, является частью для передачи int. Итак, вам нужно поместить extra («ключ», intValue) в Activty и получить int в виджете на GetIntent().getExtras().getInt(«ключ»)
В противном случае вы можете получить значение Int, используя SharedPreferences, как вы делали раньше.
Итак, допустим, в Activity:
Intent i=new Intent(Smoke_Count.this, Widget.class);
i.putExtra("count", counter);
и в виджете
Bundle bundle = getIntent().getExtras();
int yourInt = bundle.getInt("count", 0);
Редактировать
Поскольку вы уже работали с, вам лучше использовать данное intent вместо GetIntent() , это вызывает исключение NullPointerException, поэтому делайте как:
Bundle bundle = intent.getExtras();
int yourInt = bundle.getInt("count", 0);
Комментарии:
1. Ошибка при использовании метода onRecieve в activity виджета @mapo
2. можете ли вы опубликовать LogCat?
3. можете ли вы сказать, что у вас есть в строке 42 в Widget.java ?
4. это код, который находится в строке 42 int yourInt = bundle.getInt(«count», 0); @mapo