Android Studio 主活动写第二个@Override的时候报错是为啥?

图片说明

Android Studio版本是2.2版本,代码来源于《第一行代码》

尝试方法

图片说明

尝试失败

2个回答

你这个重写的应该是view的点击监听事件吧~,在你的窗体上加上这个 implements View.OnClickListener

qq_32674353
峰崽er 回复qq_40835458: public class *** extends AppCompatActivity implements View.OnClickListener
一年多之前 回复
qq_32674353
峰崽er 回复qq_40835458: 不客气
一年多之前 回复
qq_40835458
qq_40835458 回复qq_40835458:好了,谢谢
一年多之前 回复
qq_40835458
qq_40835458 在哪儿添加,我的还是错的,,,
一年多之前 回复

public class MainActivity extends AppCompatActivity implements View.OnClickListener

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
【Android studio】程序不报错但是停止运行

按照网上的视频例子在敲,但是不知道问题出在哪里,基本没有基础可言,麻烦大神们给看看,万分感谢 ``` package com.example.pet; import android.os.Bundle; import android.widget.FrameLayout; import android.widget.RadioGroup; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentTransaction; import com.example.pet.base.BaseFragment; import com.example.pet.collect.fragment.CollectFragment; import com.example.pet.community.fragment.CommunityFragment; import com.example.pet.home.fragment.HomeFragment; import com.example.pet.type.fragment.TypeFragment; import com.example.pet.user.fragment.UserFragment; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends FragmentActivity { @BindView(R.id.frameLayout) FrameLayout frameLayout; @BindView(R.id.rg_main) RadioGroup rgMain; //装多个Fragment的实例集合 private ArrayList<BaseFragment> fragments; //选中的Fragment的对应的位置 private int position; //缓存的上次显示的Fragment private Fragment tempFragemnt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //ButterKnife和当前Activity绑定,绑定后自动实例化 ButterKnife.bind(this); //初始化Fragment initFragment(); //设置RadioGroup的监听 initListener(); } private void initListener() { rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb_home://主页 position = 0; break; case R.id.rb_type://分类 position = 1; break; case R.id.rb_community://发现 position = 2; break; case R.id.rb_collect://收藏 position = 3; break; case R.id.rb_user://个人中心 position = 4; break; default: position = 0; break; } //根据位置去取不同的Fragment BaseFragment baseFragment = getFragment(position); //第一个参数:上次显示的Fragment,第二个参数:当前正要显示的Fragment switchFragment(tempFragemnt, baseFragment); } }); //默认选中主页面 rgMain.check(R.id.rb_home); } //切换Fragment,隐藏上一个,显示当前 private void switchFragment(Fragment fromFragment, BaseFragment nextFragment) { if (tempFragemnt != nextFragment) { tempFragemnt = nextFragment; if (nextFragment != null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // 判断 nextFragment 是否添加 if (!nextFragment.isAdded()) { // 隐藏当前 Fragment if (fromFragment != null) { transaction.hide(fromFragment); } //添加Fragment transaction.add(R.id.frameLayout, nextFragment).commit(); } else { // 隐藏当前 Fragment if (fromFragment != null) { transaction.hide(fromFragment); } transaction.show(nextFragment).commit(); } } } } private BaseFragment getFragment(int position) { if (fragments != null && fragments.size() > 0) { BaseFragment baseFragment = fragments.get(position); return baseFragment; } return null; } //添加的时候要按照顺序 private void initFragment() { fragments = new ArrayList<>(); fragments.add(new HomeFragment()); fragments.add(new TypeFragment()); fragments.add(new CommunityFragment()); fragments.add(new CollectFragment()); fragments.add(new UserFragment()); } } ``` 附上logcat ![图片说明](https://img-ask.csdn.net/upload/202004/19/1587281909_919389.png)![图片说明](https://img-ask.csdn.net/upload/202004/19/1587281920_250438.png)

使用Android studio编写的程序,写好代码后运行app到模拟器的时候会闪退

希望懂的大佬能帮帮忙,救救我,这个问题困扰我好久了,这个问题没解决就无法进行下一步。 1.最近使用Android studio编写了一个程序,写好代码后运行app到模拟器的时候会闪退(创建时程序版本和模拟器版本相同为5.1)。没有写代码时(也就是刚创建好程序,没添加任何东西时),在模拟器中能正常运行,但是当我写好代码后,运行app到模拟器上就会闪退了。 2.在代码部分,我是根据的SuperMap iMobile 9D(2019) for Android Guide的指导书写的,现在我也配置了许可,但还是会闪退 3.各个部分的代码如下: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.loadscence"> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboardHidden|orientation|screenSize" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <supports-screens android:largeScreens="true" android:resizeable="true" android:normalScreens="true" android:anyDensity="true"/> </manifest> ///////////////////////////////////////////////////////////这是mainactivity.java的代码 package com.example.loadscence; import androidx.appcompat.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ZoomControls; import com.supermap.data.Environment; import com.supermap.data.Workspace; import com.supermap.data.WorkspaceConnectionInfo; import com.supermap.data.WorkspaceType; import com.supermap.mapping.MapControl; import com.supermap.mapping.MapView; public class MainActivity extends AppCompatActivity { private MapControl m_mapcontrol = null; private Workspace m_workspace; private MapView m_mapView; private ZoomControls m_zoom; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置一些系统需要用到的路径 String rootPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); Environment. setLicensePath (rootPath + "/SuperMap/license/"); Environment. setTemporaryPath (rootPath + "/SuperMap/temp/"); Environment. setWebCacheDirectory (rootPath + "/SuperMap/WebCatch"); //组件功能必须在 Environment 初始化之后才能调用 Environment. initialization (this); //如果机器中默认不包括需要显示的字体,可以把相关字体文件放在参数所代表的路径中。 //例如,如果需要显示阿拉伯文字(若机器中原先不包括相关字体文件),可以把需要的字体文件放在参数所代表的路径中。 Environment. setFontsPath (rootPath + "/SuperMap/fonts/"); setContentView(R.layout. activity_main ); //打开工作空间 m_workspace = new Workspace(); WorkspaceConnectionInfo info = new WorkspaceConnectionInfo(); info.setServer(rootPath + "/SampleData/GeometryInfo/World.smwu"); info.setType(WorkspaceType. SMWU ); m_workspace.open(info); //将地图显示控件和工作空间关联 m_mapView = (MapView)findViewById(R.id. Map_view ); m_mapcontrol = m_mapView.getMapControl(); m_mapcontrol.getMap().setWorkspace(m_workspace); //打开工作空间中的第二幅地图 String mapName = m_workspace.getMaps().get(1); m_mapcontrol.getMap().open(mapName); m_zoom = (ZoomControls)findViewById(R.id. zoomControls1 ); m_mapView = (MapView)findViewById(R.id. Map_view ); m_zoom.setIsZoomInEnabled(true); m_zoom.setIsZoomOutEnabled(true); //放大按钮 m_zoom.setOnZoomInClickListener(new OnClickListener() { public void onClick(View v) { m_mapcontrol.getMap().zoom(2); m_mapcontrol.getMap().refresh(); } }); //缩小按钮 m_zoom.setOnZoomOutClickListener(new OnClickListener(){ public void onClick(View v) { m_mapcontrol.getMap().zoom(0.5); m_mapcontrol.getMap().refresh(); } }); m_mapcontrol.getMap().refresh(); } } ///////////////////////////////////////////////////////////这是activity的代码 <?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <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:id="@+id/main"> <RelativeLayout android:gravity="left" android:layout_width="match_parent" android:layout_height="match_parent"> <com.supermap.mapping.MapView android:id = "@+id/Map_view" android:layout_width="match_parent" android:layout_height = "match_parent"> </com.supermap.mapping.MapView> <ZoomControls android:id="@+id/zoomControls1" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_centerHorizontal="true" android:layout_width="wrap_content" android:layout_height="wrap_content"> </ZoomControls> </RelativeLayout> </RelativeLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> ///////////////////////////////////////////////////////////报错日志如下: 03-23 22:32:10.438 22856-22856/com.example.loadscence E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.loadscence, PID: 22856 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.loadscence/com.example.loadscence.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.NullPointerException: Attempt to get length of null array at com.supermap.data.Environment.checkAndLoadLibrary64(Environment.java:1632) at com.supermap.data.Environment.initialization(Environment.java:576) at com.example.loadscence.MainActivity.onCreate(MainActivity.java:33) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  at android.app.ActivityThread.access$800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  ```

Android studio写AIDL时报错:Execution failed for task,

我用的是Android Studio 1.4 ![图片说明](https://img-ask.csdn.net/upload/201604/20/1461137087_410343.png) ![图片说明](https://img-ask.csdn.net/upload/201604/20/1461137380_344758.png) 第二张图compile sdk version那里只能选api level 23. 在aidl包下我写了2个aidl文件,另外MainActivity那个包中的MyParcelClass,这3个和aidl有关。下面贴下代码: MyParcelClass.java ``` public class MyParcelableClass implements Parcelable { private int id; private String str; public MyParcelableClass(int id,String str) { this.id=id; this.str=str; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out,int flags) { out.writeInt(id); out.writeString(str); } private MyParcelableClass(Parcel in) { id=in.readInt(); str=in.readString(); } public static final Parcelable.Creator<MyParcelableClass> CREATOR=new Parcelable.Creator<MyParcelableClass>() { @Override public MyParcelableClass[] newArray(int size) { return new MyParcelableClass[size]; } public MyParcelableClass createFromParcel(Parcel in) { return new MyParcelableClass(in); } }; } ``` MyParcelClass.aidl: ``` package com.example.dell_pc.aldl; parcelable MyParcelableClass; ``` IMyParcelManager.aidl: ``` package com.example.dell_pc.aldl.aidl; import com.example.dell_pc.aldl.MyParcelableClass; // Declare any non-default types here with import statements interface IMyParcelManager { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); void add(in MyParcelableClass mMyParcelableClass); MyParcelableClass get(); } ``` 与aidl有关的3个文件的代码如上,报这个错误好像是Android Studio不会自动生成IMyParcelmanager.java?但是我build,然后make project后就是这个样子,求解决方法,网上搜索的方法都不行

Android Studio 中Button控件的问题

目前在参考《第一行代码Android 第二版》 看到书中 第2.2.4节 在活动中使用Toast 其中我在写码Button的时候我的AS会报错 ![图片说明](https://img-ask.csdn.net/upload/201910/13/1570978836_981403.png) 附MainActivity.kt的代码 ``` package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState); setContentView(R.layout.first_layout); Button button_1 = (Button) findViewById(R.id.button_1); button1 .setOnClickListener(new View.onClickListener) { @Override public void onClick(View v){ Toast.makeText(MainActivity.this,"You Clcke Button 1",Toast.LENGTH_SHORT).show(); } }; } } ``` 谢谢@王能指出代码没贴出来 此上为问题代码![图片说明](https://img-ask.csdn.net/upload/201910/15/1571136452_474511.png)

求求大佬救命,弄了几天不对,我自学的第一行代码,用Androidstudio 3.6.2

``` public class MainActivity extends AppCompatActivity { private EditText edit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit=(EditText)findViewById(R.id.edit); } protected void onDestroy(){ super.onDestroy(); String inputText=edit.getText().toString(); save(inputText); } public void save(String inputText){ FileOutputStream out=null; BufferedWriter writer=null; try{ out=openFileOutput("data", Context.MODE_PRIVATE); writer=new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); }catch (IOException e){ e.printStackTrace(); }finally { try{ if(writer!=null){ writer.close(); } }catch (IOException e){ e.printStackTrace(); } } } } ```

在Android Studio中读取创建的data.txt内部存储数据具体应该怎么写代码,有人帮忙看一下吗,我一直都会报错

public class WriteActivity extends AppCompatActivity { private Button save; private EditText etwrite; private TextView show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_write); save = (Button) findViewById(R.id.save); etwrite = (EditText) findViewById(R.id.et_write); show = (TextView) findViewById(R.id.tv_show); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //show.setText(write.getText().toString()); String write = etwrite.getText().toString().trim(); //public void save(String EditText){//inputText为传入的要保存的数据 FileOutputStream out = null; BufferedWriter writer = null; try { out = openFileOutput("data", Context.MODE_APPEND);//"data"为文件名,第二个参数为文件操作模式:文件已经存在,就往文件里面追加类容,不从新创建文件。 writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(write); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } // } //读取数据 } }); } }

安卓运行报错android.content.ActivityNotFoundException: Unable to find explicit activity class

以下是报错信息: ``` android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.helloworld/android.widget.TextView}; have you declared this activity in your AndroidManifest.xml? ``` 然后我搜索了一下得到的解决方案是没有将activity在mainfest.xml中注册,但是我已经注册过了,以下是xml中的代码 ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloworld"> <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"> <activity android:name=".TextViewActivity" android:label=""></activity>//注册第二个活动 <activity android:name=".MainActivity"> //前面的点是包名省略, <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> ``` 以下是第二个活动的代码 ``` package com.example.helloworld; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Paint; import android.os.Bundle; import android.widget.TextView; public class TextViewActivity extends AppCompatActivity { private TextView tv2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_text_view); tv2 = findViewById(R.id.tv2); tv2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//加入划线 tv2.getPaint().setAntiAlias(true);//去除锯齿 } } ``` 以下是第二个活动的xml代码 ``` <?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:gravity="center_horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tv_test1" android:textColor="#000000" android:textSize="30sp" />//在strings.xml中编辑好后,在这里调用 //最大行数为一,且显示不下时出现省略号 <TextView android:layout_width="100dp" android:layout_height="wrap_content" android:maxLines="1" android:ellipsize="end" android:id="@+id/t2" android:text="哎哟不错哦!" android:textColor="#000000" android:textSize="30sp"/> //有额外选项或者下拉框(大致这个意思) <TextView android:layout_width="match_parent" android:layout_height="50dp" android:drawableRight="@drawable/arrow3" android:text="for you and me" android:textColor="#000000" android:textSize="30sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="xxx" android:id="@+id/tv2" android:textColor="#000000" android:textSize="30sp" /> </LinearLayout> ``` 以下是mainactivity的代码(之后补充的) ``` public class MainActivity extends AppCompatActivity { private Button btntv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//设置内容视图 btntv = findViewById(R.id.bt_tv1); btntv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //跳转到TextView演示界面 Intent intent = new Intent(MainActivity.this, TextView.class); startActivity(intent); } }); } } ```

树莓派与Android的一个简单问题,本人小白,解决不了了,求大神帮助!!!

# mainactivity ``` package com.example.rasberrypi; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Message; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; import java.util.TimerTask; public class MainActivity extends Activity { private Handler mHandler; private TextView fire, people; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHandler = new Handler(); mHandler.post(new TimerProcess()); fire = findViewById(R.id.fire); people = findViewById(R.id.people); } @SuppressLint("HandlerLeak") final Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { String ret = msg.obj.toString(); switch (msg.what){ case 1: StringBuilder builder = new StringBuilder(); JSONObject jsonObject = null; try { jsonObject = new JSONObject(ret); Log.i("json", ""+jsonObject); if (jsonObject.getInt("isFire") == 0) { fire.setText("没有发现火焰"); fire.setTextColor(android.graphics.Color.GREEN); } else { fire.setText("发现火焰"); fire.setTextColor(android.graphics.Color.RED); mes("火焰传感器探测到火焰!"); } if (jsonObject.getInt("isInvaded") == 0) { people.setText("安全"); people.setTextColor(android.graphics.Color.GREEN); } else { people.setText("发现入侵者"); people.setTextColor(android.graphics.Color.RED); mes("发现有人进入房间!"); } } catch (JSONException e) { e.printStackTrace(); } break; default: break; } } }; private void getDevInformation(){ new Thread(new Runnable() { @Override public void run() { String ret = Webconn.getDev(); System.out.println("get return:"); System.out.println(ret); handler.sendMessage(handler.obtainMessage(1, ret)); } }).start(); } private class TimerProcess implements Runnable{ @Override public void run() { mHandler.postDelayed(this, 5000); getDevInformation(); } } private void mes(String m) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); Notification.Builder builder = new Notification.Builder(MainActivity.this); builder.setSmallIcon(R.mipmap.ic_launcher); //设置图标 builder.setTicker("显示第二个通知"); builder.setContentTitle("树莓派安防"); //设置标题 builder.setContentText(m); //消息内容 builder.setWhen(System.currentTimeMillis()); //发送时间 builder.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光 builder.setAutoCancel(true);//打开程序后图标消失 /*空一句*/ Intent intent = new Intent(MainActivity.this,Activity.class); PendingIntent pendingIntent =PendingIntent.getActivity(MainActivity.this, 0, intent, 0); builder.setContentIntent(pendingIntent); Notification notification = builder.build(); mNotificationManager.notify(1, notification); } } ``` # webconn ``` package com.example.rasberrypi; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Webconn { public static String getDev(){ String url = "http://192.168.1.104:5000/state/"; try { URL url1 = new URL(url); HttpURLConnection urlConnection =(HttpURLConnection) url1.openConnection(); int code = urlConnection.getResponseCode(); if(code == 200){ String strResult = urlConnection.getResponseMessage(); System.out.println(strResult); return strResult; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "null"; } } ``` # activity_main ``` <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.rasberrypi.MainActivity"> <TextView android:id="@+id/fire" android:layout_width="297dp" android:layout_height="95dp" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.135" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.225" /> <TextView android:id="@+id/people" android:layout_width="300dp" android:layout_height="88dp" tools:ignore="MissingConstraints" tools:layout_editor_absoluteX="10dp" tools:layout_editor_absoluteY="236dp" /> </android.support.constraint.ConstraintLayout> ``` 这里是代码,但是我的运行结果是空白图 ![图片说明](https://img-ask.csdn.net/upload/201802/21/1519186237_346292.png) Android studio中说 mainactivity中间的 jsonObject = new JSONObject(ret); String ret = Webconn.getDev(); 和webconn中的 int code = urlConnection.getResponseCode(); 报错 192.168.1.104出来的内容是 ![图片说明](https://img-ask.csdn.net/upload/201802/21/1519186346_762454.png) 希望大神可以帮忙解决

android下载图片过大导致报错

package tarena.day2801; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; public class MainActivity extends Activity { private Button button; private ImageView img; private String image_Path = "http://2.javatl.sinaapp.com/images/51d8c1d77fed4.jpg"; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button1); img = (ImageView) findViewById(R.id.imageView1); LinearLayout rl = (LinearLayout) findViewById(R.id.lr); ImageView img = new ImageView(this); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int height = dm.heightPixels/3; int width = dm.widthPixels / 2; LayoutParams params = new LayoutParams(width, height); img.setLayoutParams(params); rl.setGravity(Gravity.CENTER); img.setImageResource(R.drawable.ic_launcher); dialog = new ProgressDialog(this); dialog.setTitle("提示信息"); dialog.setMessage("正在下载,请稍候..."); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new MYTask().execute(image_Path); } }); } /** * 使用异步任务的规则: 1、申明的类继承AsyncTask 标注三个参数的类型 * 2、第一个参数表示要执行的任务,通常是网络的路径;第二个参数表示进度的刻度,第三个参数表示任务执行的返回结果 * * @author liende * */ public class MYTask extends AsyncTask<String, Void, Bitmap> { /** * 表示任务执行之前的操作 */ @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog.show(); } /** * 主要是完成耗时的操作 */ @Override protected Bitmap doInBackground(String... arg0) { // TODO Auto-generated method stub // 使用网络连接类HttpClient类王城对网络数据的提取 HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(arg0[0]); Bitmap bitmap = null; try { HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = httpResponse.getEntity(); byte[] data = EntityUtils.toByteArray(httpEntity); bitmap = BitmapFactory .decodeByteArray(data, 0, data.length); ## **//在这里调用压缩方法** bitmap = compressImage(bitmap); } } catch (Exception e) { // TODO: handle exception } return bitmap; } /** * 主要是更新UI的操作 */ @Override protected void onPostExecute(Bitmap bitmap) { // TODO Auto-generated method stub super.onPostExecute(bitmap); Bitmap bmcopy = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); Paint paint = new Paint(); Canvas canvas = new Canvas(bmcopy); Matrix mt = new Matrix(); mt.setRotate(30, bmcopy.getWidth()/2, bmcopy.getHeight()/2); //mt.setScale(0.5f, 2); canvas.drawBitmap(bitmap, mt, paint); img.setImageBitmap(bmcopy); dialog.dismiss(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } ** //图片压缩方法** private Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while ( baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();//重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 options -= 10;//每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片 return bitmap; } } 明明调用了图片压缩方法,但是不知道为什么运行的时候还是崩溃

安卓点击按钮不能实现跳转 模拟器运行软件点按钮就闪退

点登录按钮就闪退![图片说明](https://img-ask.csdn.net/upload/201906/28/1561723660_759733.jpg) 下面是代码 ```package com.example.test; import android.app.Activity; import com.example.test.R; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Denglu extends Activity { Button denglu,zhuche; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.denglu); denglu=(Button)findViewById(R.id.denglu); zhuche=(Button)findViewById(R.id.zhuche); denglu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(Denglu.this,RegisterActivity.class); startActivity(intent); } }); zhuche.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //为了跳转到注册界面,并实现注册功能 Intent intent=new Intent(Denglu.this,LostFindActivity.class); startActivity(intent); finish(); } }); } } ``` 第二个 package com.example.test; import android.app.Activity; import com.example.test.R; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class LostFindActivity extends Activity { Button register; protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.zc); register =(Button)findViewById(R.id.register); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(LostFindActivity.this,RegisterActivity.class); startActivity(intent); Toast.makeText(LostFindActivity.this, "注册成功,跳转中", Toast.LENGTH_LONG).show(); finish(); } }); } } 第三个 package com.example.test; import com.example.test.MainActivity; import com.example.test.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class RegisterActivity extends Activity { Button denglu; protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.dl); denglu=(Button)findViewById(R.id.denglu); denglu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(RegisterActivity.this,MainActivity.class); startActivity(intent); Toast.makeText(RegisterActivity.this, "登录成功,跳转中", Toast.LENGTH_LONG).show(); finish(); } }); } } 跳转不了 思路是先注册然后登陆 进主界面 下面是报错信息 ![图片说明](https://img-ask.csdn.net/upload/201906/28/1561724541_821567.jpg) 萌新一个 求各位大佬帮帮忙

请问Android放了AdView控件调试之后又删除了,再调试就一直闪退打不开是为什么?

如题,安卓初学者,没有什么复杂功能,只是拖上去又删掉了 ``` <?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.095" /> <RadioGroup android:id="@+id/radioGroup" android:layout_width="263dp" android:layout_height="131dp" android:layout_marginStart="72dp" android:layout_marginTop="104dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2"> <RadioButton android:id="@+id/rbFirst" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="hh " /> <RadioButton android:id="@+id/rbSecond" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="hoho" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/rgText" /> </RadioGroup> <Button android:id="@+id/btnOne" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="72dp" android:layout_marginTop="72dp" android:text="@string/txtBtnOne" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/radioGroup" /> <CheckBox android:id="@+id/checkBox2" android:layout_width="82dp" android:layout_height="31dp" android:layout_marginTop="40dp" android:layout_marginEnd="12dp" android:text="@string/txtcb2" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/checkBox" /> <CheckBox android:id="@+id/checkBox" android:layout_width="80dp" android:layout_height="33dp" android:layout_marginTop="56dp" android:layout_marginEnd="16dp" android:text="@string/txtcb1" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/radioGroup" app:layout_constraintVertical_bias="0.2" /> <CheckBox android:id="@+id/checkBox3" android:layout_width="81dp" android:layout_height="30dp" android:layout_marginTop="64dp" android:layout_marginEnd="16dp" android:layout_marginBottom="51dp" android:text="@string/txtcb3" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/checkBox2" app:layout_constraintVertical_bias="0.0" /> <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginBottom="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> ``` ``` class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnOne.setOnLongClickListener(View.OnLongClickListener { (it as Button).text = this.getString(R.string.txtBtnChanged) true }) btnOne.setOnClickListener(View.OnClickListener { click2Next() }) radioGroup.setOnCheckedChangeListener{ group, checkedId -> textView2.text = when(checkedId){ R.id.rbFirst -> "第一个" R.id.rbSecond -> "第二个" else ->"" } } checkBox.setOnCheckedChangeListener(myOnCheckChangedListener) checkBox2.setOnCheckedChangeListener(myOnCheckChangedListener) checkBox3.setOnCheckedChangeListener(myOnCheckChangedListener) } fun click2Next(){ intent = Intent(this,NextActivity::class.java).apply { putExtra("Label",btnOne.text) } this.startActivity(intent) } private val myOnCheckChangedListener = CompoundButton.OnCheckedChangeListener{ buttonView, isChecked ->when(buttonView.id){ R.id.checkBox -> { if(isChecked){ checkBox.text="Checked" } else { checkBox.text = this.getText(R.string.txtcb1) } } R.id.checkBox2 -> { val temp = buttonView.text if(isChecked){ checkBox2.text = "Checked" } else { checkBox2.text = this.getText(R.string.txtcb2) } } R.id.checkBox3 -> { val temp = buttonView.text if(isChecked){ checkBox3.text = "Checked" } else { checkBox3.text = this.getText(R.string.txtcb3) } } } } ```

关于Android button的 setOnClickListener引用this的问题

初学Android 遇到了下面这个问题 为什么这里必须用login.this不能用this代替呢?? button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(login.this,"click button2",Toast.LENGTH_SHORT).show(); } }); } 但是菜单这里却可以直接使用this?????? 明明都是同一个活动里的。。。??? public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.add_item: Toast.makeText(this,"add",Toast.LENGTH_SHORT).show(); case R.id.remove_item: Toast.makeText(this,"remove",Toast.LENGTH_SHORT).show(); default: } return true; }

安卓开发中,我在Spinner的onItemSelected函数里访问全局变量程序就会CrashHandler闪退

小白在做一个android音乐播放器,想设置一个下拉列表来选择歌曲的播放顺序,分随机播放、按时间顺序播放和按热度播放,但是我在使用Spinner的onItemSelected函数时,在里面调用一下全局的歌曲List就会出现CrashHandler然后闪退,而且不用排序只是想打印一下list信息就会闪退,CrashHandler后面的参数不懂是什么东西,希望大佬们指点一下,下面附上代码和报错信息: ``` public void setSpinner(){ List<String> list = new ArrayList<String>(); list.add("随机播放"); list.add("播放最新"); list.add("播放最热"); adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> arg0, final View arg1, final int arg2, long arg3) { // TODO Auto-generated method stub arg0.setVisibility(View.VISIBLE); Log.i("adapter","您选择的是:"+adapter.getItem(arg2)); //以按热度排序为例 Collections.sort(musicList, new Comparator<Music>() { @Override public int compare(Music o1, Music o2){ int diff = o1.getFansnum() - o2.getFansnum(); if(diff >0) { return 1; }else if(diff < 0){ return -1; } return 0; } }); for(int i=0;i<musicList.size();i++){ Log.i("smile", "排序成功~"+musicList.get(i).getObjectId()+"lizi:"+musicList.get(i).getName()); } } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub arg0.setVisibility(View.VISIBLE); } }); } ``` 其中musicList是一个全局变量,我用传参传进函数也不行,难道是因为我的歌曲正在播放? 报错信息: D/AndroidRuntime: Shutting down VM D/CrashHandler: BOARD : unknown BOOTLOADER : unknown BRAND : google CPU_ABI : x86 CPU_ABI2 : DEVICE : generic_x86 DISPLAY : sdk_google_phone_x86-userdebug 7.0 NYC 4662066 dev-keys FINGERPRINT : google/sdk_google_phone_x86/generic_x86:7.0/NYC/4662066:userdebug/dev-keys HARDWARE : ranchu D/CrashHandler: HOST : abfarm646 ID : NYC IS_DEBUGGABLE : true IS_EMULATOR : true MANUFACTURER : Google MODEL : Android SDK built for x86 PERMISSIONS_REVIEW_REQUIRED : false PRODUCT : sdk_google_phone_x86 RADIO : unknown SERIAL : unknown SUPPORTED_32_BIT_ABIS : [Ljava.lang.String;@970f945 SUPPORTED_64_BIT_ABIS : [Ljava.lang.String;@16b589a SUPPORTED_ABIS : [Ljava.lang.String;@cfd5cb TAG : Build TAGS : dev-keys TIME : 1521319005000 TYPE : userdebug UNKNOWN : unknown USER : android-build

Button onClick事件不能运行

我创建一个viewPager,在每一个页面上有三个布局。在第二个页面上我想处理按钮事件,当点击按钮时背景颜色会变。但是现在我的代码不能运行。去掉button代码,viewPager就可以正常运行。 这是我的代码: public class ViewPagerProjectActivity extends Activity implements OnClickListener{ Button btn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ViewPagerAdapter adapter = new ViewPagerAdapter( this ); ViewPager pager = (ViewPager)findViewById( R.id.viewpager ); pager.setAdapter( adapter ); pager.setCurrentItem(0); } public void OnClick(View v) { if(v.equals(btn)) { LinearLayout l = (LinearLayout) findViewById(R.id.deneme2); l.setBackgroundDrawable(getResources().getDrawable(R.drawable.background)); } } } 错误: E/AndroidRuntime(273): FATAL EXCEPTION: main E/AndroidRuntime(273): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yahya.ViewPagerProject/com.yahya.ViewPagerProject.ViewPagerProjectActivity}: java.lang.ClassCastException: com.yahya.ViewPagerProject.ViewPagerProjectActivity E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)

android fragment广播问题

从A类跳转到B类,B类有个发送广播的按钮!第一次发送广播,在fragment中接收并执行b操作!当我退到A类,再跳转B类后,再点击按钮发送那个广播,在fragment中会执行两次b操作!我退三次,就会执行三次b操作! 这是怎么回事呢? 代码如下: B类中发送广播: Intent inten = new Intent("android.intent.action.Fa"); LocalBroadcastManager.getInstance(CommodityActivity.this).sendBroadcast(inten); 侧滑fragment接收广播: LocalBroadcastManager broadcastManager2 = LocalBroadcastManager.getInstance(getActivity()); IntentFilter intentFilter2 = new IntentFilter(); intentFilter2.addAction("android.intent.action.guafff"); BroadcastReceiver mItemViewListClickReceiver2 = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent inten) { Log.e("b操作","b操作"); } }; broadcastManager2.registerReceiver(mItemViewListClickReceiver2, intentFilter2); 打印日志: 第一次进B类:E/b操作: b操作 第二次进B类:E/b操作: b操作 E/b操作: b操作 第三次进B类:E/b操作: b操作 E/b操作: b操作 E/b操作: b操作 。。。 。。。 。。。 就这么多,我还该怎么改过来?求大神解答,甚急!甚急!! 无悬赏金币,可加QQ:379077640!需要的话,必有感谢!

android setImageDrawable()

try { URL url = new URL(itemObj.iv); // String string = String.valueOf(itemObj.iv); // URL url = new URL(string); Utils.onLoadImage(url, new Utils.OnLoadImageListener() { @Override public void OnLoadImage(Bitmap bitmap, String bitmapPath) { if (bitmap != null) { // themeViewHolder.parallaxImageView.setImageBitmap(bitmap); BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap); themeViewHolder.parallaxImageView.setImageDrawable(bitmapDrawable); // themeViewHolder.parallaxImageView.setImageDrawable(context.getResources().getDrawable(itemObj.iv)); } } }); } catch (Exception e) { e.printStackTrace(); } 各位大牛,为什么这样不能显示图片

运行到setContentView这里崩溃了

这是第一行代码里面的一个项目,运行后崩溃: ![图片说明](https://img-ask.csdn.net/upload/201702/12/1486848687_748230.jpg) MainActivity.java ``` package com.example.newsapp; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` News.java ``` package com.example.newsapp; public class News { private String title; private String content; public String getTitle() { return title; } public void setTitle(String title) { this.title=title; } public String getContent() { return content; } public void setContent(String content) { this.content=content; } } ``` NewsAdapter.java ``` package com.example.newsapp; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class NewsAdapter extends ArrayAdapter<News> { private int resourceId; public NewsAdapter(Context context,int textViewResourceId,List<News> objects) { super(context,textViewResourceId,objects); resourceId=textViewResourceId; } @Override public View getView(int position,View convertView,ViewGroup parent) { News news=getItem(position); View view; if (convertView==null) { view=LayoutInflater.from(getContext()).inflate(resourceId,null); } else { view=convertView; } TextView newsTitleText=(TextView)view.findViewById(R.id.news_title); newsTitleText.setText(news.getTitle()); return view; } } ``` NewsContentActivity.java ``` package com.example.newsapp; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.view.Window; public class NewsContentActivity extends FragmentActivity { public static void actionStart(Context context,String newsTitle,String newsContent) { Intent intent=new Intent(context,NewsContentActivity.class ); intent.putExtra("news_title",newsTitle); intent.putExtra("news_content",newsContent); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.news_content); FragmentManager fragmentManager=getSupportFragmentManager(); String newsTitle=getIntent().getStringExtra("news_title"); String newsContent=getIntent().getStringExtra("news_content"); NewsContentFragment newsContentFragment=(NewsContentFragment)fragmentManager.findFragmentById(R.id.news_content_fragment); newsContentFragment.refresh(newsTitle,newsContent); } } ``` NewsContentFragment.java ``` package com.example.newsapp; 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.TextView; public class NewsContentFragment extends Fragment { private View view; @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { view=inflater.inflate(R.layout.news_content_frag,container,false ); return view; } public void refresh(String newsTitle,String newsContent) { View visibilityLayout=view.findViewById(R.id.visibility_layout); visibilityLayout.setVisibility(View.VISIBLE); TextView newsTitleText=(TextView)view.findViewById(R.id.news_title); TextView newsContentText=(TextView)view.findViewById(R.id.news_content); newsTitleText.setText(newsTitle); newsContentText.setText(newsContent); } } ``` NewsTitleFragment.java ``` package com.example.newsapp; import java.util.ArrayList; import java.util.List; import android.app.Activity; 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.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; public class NewsTitleFragment extends Fragment implements OnItemClickListener { private ListView newsTitleListView; private List<News> newsList; private NewsAdapter adapter; private boolean isTwoPane; @Override public void onAttach(Activity activity) { super.onAttach(activity); newsList=getNews(); adapter=new NewsAdapter(activity,R.layout.news_item,newsList); } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { View view=inflater.inflate(R.layout.news_title_frag,container,false ); newsTitleListView=(ListView)view.findViewById(R.id.news_title_list_view); newsTitleListView.setAdapter(adapter); newsTitleListView.setOnItemClickListener(this ); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (getActivity().findViewById(R.id.news_content_layout)!=null ) isTwoPane=true; else isTwoPane=false; } @Override public void onItemClick(AdapterView<?> parent,View view,int position,long id) { News news=newsList.get(position); if (isTwoPane) { NewsContentFragment newsContentFragment=(NewsContentFragment)getFragmentManager().findFragmentById(R.id.news_content_fragment); newsContentFragment.refresh(news.getTitle(),news.getContent()); } else { NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent()); } } private List<News> getNews() { List<News> newsList=new ArrayList<News>(); News news1=new News(); news1.setTitle("标题"); news1.setContent("内容"); newsList.add(news1); News news2=new News(); news2.setTitle("日记"); news2.setContent("去旅游"); newsList.add(news2); return newsList; } } ```

尝试使用Intent跳转至新Activity时程序停止运行

``` package com.level1.yukinoshita.swan0; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.level1.yukinoshita.fragment.Fragment_autocharge; import com.level1.yukinoshita.fragment.Fragment_replyaction; import com.level1.yukinoshita.fragment.Fragment_searchall; import com.level1.yukinoshita.fragment.Fragment_socialaction; import com.level1.yukinoshita.fragment.Fragment_socialuser; import com.level1.yukinoshita.fragment.Fragment_userfavor; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { // private RecyclerView contentRecyclerView; // private List<String> recycleViewData; // private RecycleViewSimpleAdapter contentRecyclerViewAdapter; private static final int STACK=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle(""); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "正在刷新", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_socialuser) { // 分配对应Fragment Fragment_socialuser fragment = new Fragment_socialuser(); getFragmentManager().beginTransaction().replace(R.id.main_contentview, fragment).commit(); } else if (id == R.id.nav_socialaction) { Fragment_socialaction fragment = new Fragment_socialaction(); getFragmentManager().beginTransaction().replace(R.id.main_contentview, fragment).commit(); } else if (id == R.id.nav_autocharge) { Fragment_autocharge fragment = new Fragment_autocharge(); getFragmentManager().beginTransaction().replace(R.id.main_contentview, fragment).commit(); } else if (id == R.id.nav_replyaction) { Fragment_replyaction fragment = new Fragment_replyaction(); getFragmentManager().beginTransaction().replace(R.id.main_contentview, fragment).commit(); } else if (id == R.id.nav_userfavor) { Fragment_userfavor fragment = new Fragment_userfavor(); getFragmentManager().beginTransaction().replace(R.id.main_contentview, fragment).commit(); } else if (id == R.id.nav_searchall) { Fragment_searchall fragment = new Fragment_searchall(); getFragmentManager().beginTransaction().replace(R.id.main_contentview, fragment).commit(); } else if (id == R.id.nav_settings) { // 使用Activity Intent intent = new Intent(this, Activity_settings.class); startActivity(intent); } else if (id == R.id.nav_developer) { // 使用Activity } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } } ``` 报错信息如下 04-15 01:34:22.769 6114-6114/com.level1.yukinoshita.swan0 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.level1.yukinoshita.swan0, PID: 6114 android.content.ActivityNotFoundException: Unable to find explicit activity class {com.level1.yukinoshita.swan0/com.level1.yukinoshita.swan0.Activity_settings}; have you declared this activity in your AndroidManifest.xml? at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794) at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512) at android.app.Activity.startActivityForResult(Activity.java:3917) at android.app.Activity.startActivityForResult(Activity.java:3877) at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842) at android.app.Activity.startActivity(Activity.java:4200) at android.app.Activity.startActivity(Activity.java:4168) at com.level1.yukinoshita.swan0.MainActivity.onNavigationItemSelected(MainActivity.java:125) at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:151) at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811) at android.support.v7.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:84) at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152) at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958) at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:318) at android.view.View.performClick(View.java:5198) at android.view.View$PerformClick.run(View.java:21147) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 04-15 01:34:24.908 6114-6114/com.level1.yukinoshita.swan0 I/Process: Sending signal. PID: 6114 SIG: 9

安卓开发 当返回之前的fragment 如何防止LiveData.observe()里的方程再次被触发?

最近刚学安卓开发,目前在使用mvvm模式进行开发。我发现LiveData有一个很有意思的属性: (https://developer.android.com/topic/libraries/architecture/livedata?hl=zh-cn) 通常,LiveData 仅在数据发生更改时才发送更新,并且仅发送给活跃观察者。此行为的一种例外情况是,观察者从非活跃状态更改为活跃状态时也会收到更新。此外,如果观察者第二次从非活跃状态更改为活跃状态,则只有在自上次变为活跃状态以来值发生了更改时,它才会收到更新。 这给我造成了些麻烦。比如说,当我返回上一个fragment时, 这个fragment会马上运行observe(),观察到的数据则是上一次运行得到的数据。我在观察方程里有关于view组建的reference。当观察方程立刻被触发时,有时候这些组件还没initialize完毕而造成npe。 我自己的例子是这样的:我有一个登陆的界面,用户按下登陆键view就会把记录下的用户名和密码(用一个searchEvent的类表示)传给viewmodel, viewmodel会把用Transformations.switchMap()来调用repository里的retrofit API同时view里有一个观察这个活动的方程。点击登陆登陆成功后,在那个fragment(我称之为fragment B)如果我按返回返回这个登陆界面,他会马上登陆成功,再次回到fragmentB里 请问该如何防止这种情况呢? 这是我viewmodel的代码: ``` public class LoginViewModel extends BaseViewModel<LoginRepository> { private final MutableLiveData<LoginEvent> loginEventMutableLiveData = new MutableLiveData<>(); private final LiveData<RemoteResponse<UserInfo>> remoteResponseMutableLiveData = Transformations .switchMap(loginEventMutableLiveData, repository::login); private final MutableLiveData<String> errMsgMutableLiveData = new MutableLiveData<>(); LoginViewModel(LoginRepository baseRepository) { super(baseRepository); } public LiveData<RemoteResponse<UserInfo>> getRemoteResponseMutableLiveData() { return remoteResponseMutableLiveData; } public MutableLiveData<String> getErrMsgMutableLiveData() { return errMsgMutableLiveData; } public void login(LoginEvent loginEvent) { if (Utils.isNullOrEmpty(loginEvent.userId)) { errMsgMutableLiveData.setValue("Please enter a valid password!"); return; } if (Utils.isNullOrEmpty(loginEvent.password)) { errMsgMutableLiveData.setValue("Please enter a valid password!"); return; } loginEventMutableLiveData.setValue(loginEvent); } } ``` 这是我loginfragment的代码: ``` public class LoginFragment extends BaseFragment<LoginViewModel, LoginRepository> { private LoginFragmentBinding binding; private NavigationManager navigationManager; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = LoginFragmentBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); navigationManager = (NavigationManager) context; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); binding.btnLogin.setOnClickListener( v -> { viewModel.login(new LoginEvent(binding.etUserIdLogin.getText().toString(), Utils.md5Encryption(binding.etPasswordLogin.getText().toString()))); // faker user info }); viewModel.getRemoteResponseMutableLiveData().observe(getViewLifecycleOwner(), it -> { if (it != null && it.status.equals("OK")) { Utils.constructToast(getContext(), "Login success!").show(); Config.userId = it.response.userId; Config.name = it.response.name; navigationManager.navigateTo(new HomeListFragment()); } else { Utils.constructToast(getContext(), it == null ? "Error !" : it.status).show(); } }); viewModel.getErrMsgMutableLiveData().observe(getViewLifecycleOwner(), it -> { Utils.constructToast(getContext(), it).show(); }); } @Override protected LoginViewModel getViewModel() { return new ViewModelProvider(requireActivity(), getFactory()).get(LoginViewModel.class); } @Override protected ViewModelProvider.Factory getFactory() { return new ViewModelProvider.Factory() { @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { return (T) new LoginViewModel(getRepository()); } }; } @Override protected LoginRepository getRepository() { return new LoginRepository(); } } ``` 补充:我寻思Transformation.distinctUntilChange()可能有用,但是用了好像没效果,不知道是不是这么用 ``` private final LiveData<RemoteResponse<UserInfo>> remoteResponseMutableLiveData = Transformations.distinctUntilChange(Transformations .switchMap(loginEventMutableLiveData, repository::login))); ``` 我听说把viewmodel的东西手动清空也可以,但不知道怎么清空

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

立方体线框模型透视投影 (计算机图形学实验)

计算机图形学实验 立方体线框模型透视投影 的可执行文件,亲测可运行,若需报告可以联系我,期待和各位交流

2019 AI开发者大会

2019 AI开发者大会

组成原理课程设计(实现机器数的真值还原等功能)

实现机器数的真值还原(定点小数)、定点小数的单符号位补码加减运算、定点小数的补码乘法运算和浮点数的加减运算。

C/C++跨平台研发从基础到高阶实战系列套餐

一 专题从基础的C语言核心到c++ 和stl完成基础强化; 二 再到数据结构,设计模式完成专业计算机技能强化; 三 通过跨平台网络编程,linux编程,qt界面编程,mfc编程,windows编程,c++与lua联合编程来完成应用强化 四 最后通过基于ffmpeg的音视频播放器,直播推流,屏幕录像,

MFC一站式终极全套课程包

该套餐共包含从C小白到C++到MFC的全部课程,整套学下来绝对成为一名C++大牛!!!

软件测试2小时入门

软件测试2小时入门

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

计算机图形学-球的光照模型课程设计

计算机图形学-球的光照模型,有代码完美运行,有课程设计书

Linux常用命令大全(非常全!!!)

Linux常用命令大全(非常全!!!) 最近都在和Linux打交道,感觉还不错。我觉得Linux相比windows比较麻烦的就是很多东西都要用命令来控制,当然,这也是很多人喜欢linux的原因,比较短小但却功能强大。我将我了解到的命令列举一下,仅供大家参考: 系统信息 arch 显示机器的处理器架构 uname -m 显示机器的处理器架构 uname -r 显示正在使用的内核版本 d...

因为看了这些书,我大二就拿了华为Offer

四年了,四年,你知道大学这四年我怎么过的么?

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

fakeLocation13.5.1.zip

fakeLocation13.5.1 虚拟定位 ios13.5.1的最新驱动下载,iPhone/iPad免越狱虚拟定位工具Location-cleaned驱动已更新

UnityLicence

UnityLicence

Python可以这样学(第一季:Python内功修炼)

Python可以这样学(第一季:Python内功修炼)

Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

土豆浏览器

土豆浏览器可以用来看各种搞笑、电影、电视剧视频

【数据结构与算法综合实验】欢乐连连看(C++ & MFC)案例

这是武汉理工大学计算机学院数据结构与算法综合实验课程的第三次项目:欢乐连连看(C++ & MFC)迭代开发代码。运行环境:VS2017。已经实现功能:开始游戏、消子、判断胜负、提示、重排、计时、帮助。

php+mysql学生成绩管理系统

学生成绩管理系统,分三个模块:学生,教师和管理员。 管理员模块:负责学生、老师信息的增删改;发布课程信息的增删改,以便让学生选课;审核老师提交的学生成绩并且打印成绩存档;按照课号查询每个课号的学生成绩

多功能数字钟.zip

利用数字电子计数知识设计并制作的数字电子钟(含multisim仿真),该数字钟具有显示星期、24小时制时间、闹铃、整点报时、时间校准功能

推荐24个国外黄色网站欣赏

在中国清朝,明黄色的衣服只有皇子才有资格穿,慢慢的黄色在中国就成了高贵的颜色。在人们的色彩印象中,黄色也表现为暂停。所以当你的网页设计采用黄色的时候,会让人们在你的网页前停留。 黄色,就像橙色和红色,黄色也是一个暖色。它有大自然、阳光、春天的涵义,而且通常被认为是一个快乐和有希望的色彩。黄色是所有色相中最能发光的颜色,给人轻快,透明,辉煌,充满希望的色彩印象。 黄色是一个高可见的色...

u-boot-2015.07.tar.bz2

uboot-2015-07最新代码,喜欢的朋友请拿去

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

学生成绩管理系统(PHP + MYSQL)

做的是数据库课程设计,使用的php + MySQL,本来是黄金搭配也就没啥说的,推荐使用wamp服务器,里面有详细的使用说明,带有界面的啊!呵呵 不行的话,可以给我留言!

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

C++语言基础视频教程

C++语言基础视频教程

玩转Python-Python3基础入门

玩转Python-Python3基础入门

相关热词 c# 开发接口 c# 中方法上面的限制 c# java 时间戳 c#单元测试入门 c# 数组转化成文本 c#实体类主外键关系设置 c# 子函数 局部 c#窗口位置设置 c# list 查询 c# 事件 执行顺序
立即提问
相关内容推荐