Android about unable to start activity componentinfo - java

I'm a new programmer,recently i have a bug but can't solve
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.Bl
uetoothChat/com.example.android.BluetoothFileTran.FileTranActivity}:
java.lang.NullPointerException
logcat stack trace
04-26 10:19:43.613: E/BluetoothChat(21754): +++ ON CREATE +++
04-26 10:19:44.213: E/CheckPermission(21754): _bluetooth code = 1
04-26 10:19:44.213: E/BluetoothChat(21754): ++ ON START ++
04-26 10:19:44.233: E/BluetoothChat(21754): + ON RESUME +
04-26 10:19:44.233: E/CheckPermission(21754): _bluetooth code = 13
04-26 10:19:45.643: E/BluetoothChat(21754): - ON PAUSE -
04-26 10:19:47.223: E/BluetoothChat(21754): + ON RESUME +
04-26 10:19:55.093: E/BluetoothChat(21754): - ON PAUSE -
04-26 10:20:21.363: E/AndroidRuntime(21754): FATAL EXCEPTION: main
04-26 10:20:21.363: E/AndroidRuntime(21754): Process: com.example.android.BluetoothChat, PID: 21754
04-26 10:20:21.363: E/AndroidRuntime(21754): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.BluetoothChat/com.example.android.BluetoothFileTran.FileTranActivity}: java.lang.NullPointerException
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2190)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.access$800(ActivityThread.java:139)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.os.Looper.loop(Looper.java:136)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.main(ActivityThread.java:5049)
04-26 10:20:21.363: E/AndroidRuntime(21754): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:818)
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
04-26 10:20:21.363: E/AndroidRuntime(21754): at dalvik.system.NativeStart.main(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): Caused by: java.lang.NullPointerException
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.example.android.BluetoothFileTran.FileTranActivity.onCreate(FileTranActivity.java:66)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Activity.performCreate(Activity.java:5293)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Activity.performCreate(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
04-26 10:20:21.363: E/AndroidRuntime(21754): ... 12 more
here is Bluetoooth.java
package com.example.android.BluetoothChat;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothChat.service.BluetoothChatService;
import com.example.android.BluetoothFileTran.FileTranActivity;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BluetoothChat extends Activity {
public static final String SEND_FILE_NAME = "sendFileName";
public static final int REQUEST_FILE = 1000;
private static String mSendFileName ;
private Handler mOthHandler;
private static String mAddress ;
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private String mConnectedDeviceName = null;
private ArrayAdapter<String> mConversationArrayAdapter;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
setContentView(R.layout.main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (mChatService == null) setupChat();
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
mChatService = new BluetoothChatService(this, mHandler);
mOutStringBuffer = new StringBuffer("");
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
if (mChatService != null) {
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
mChatService.start();
}
}
}
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
//EditorInfo.IME_NULL KeyEvent.ACTION_UP
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void sendMessage(String message) {
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
mChatService.write(send);
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
// mAddress = msg.getData().getString(DEVICE_ADDRESS);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
mAddress = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mAddress);
mChatService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
setupChat();
} else {
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
break;
case REQUEST_FILE:
if (resultCode == Activity.RESULT_OK) {
mSendFileName = data.getExtras().getString(SEND_FILE_NAME);
doSendFileByBluetooth();
}
break;
}
}
private void doSendFileByBluetooth() {
String filePath = mSendFileName.trim();
if(!filePath.equals("null")){
if(null == mOthHandler){
HandlerThread handlerThread = new HandlerThread("other_thread");
handlerThread.start();
mOthHandler = new Handler(handlerThread.getLooper());
}
mOthHandler.post(new Runnable() {
#Override
public void run() {
ContentValues cv = new ContentValues();
String uri = "file://" + mSendFileName.trim();
cv.put("uri", uri);
cv.put("destination", mAddress.trim());
cv.put("direction", 0);
Long ts = System.currentTimeMillis();
cv.put("timestamp", ts);
getContentResolver().insert(Uri.parse("content://com.android.bluetooth.opp/btopp"), cv);
}
});
}else {
Toast.makeText(BluetoothChat.this, "请选择要发送的文件!", Toast.LENGTH_LONG).show();
}
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
case R.id.file_transport:
Intent fileIntent = new Intent(this, FileTranActivity.class);
startActivityForResult(fileIntent, REQUEST_FILE);
return true;
}
return false;
}
}
here is FileTranActivity.java
package com.example.android.BluetoothFileTran;
import java.io.File;
import com.example.android.BluetoothChat.BluetoothChat;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothFileTran.adapter.AdapterManager;
import com.example.android.BluetoothFileTran.adapter.FileListAdapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class FileTranActivity extends Activity {
ListView mFileListView;
FileListAdapter mFileListAdapter;
AdapterManager mAdapterManager;
private Handler mOtherHandler;
private Runnable updateFileListRunnable;
private File file;
private String sdcardPath;
private String path;
Button mBackBtn;
Button mEnsureBtn;
Button mCancelBtn;
TextView mLastClickView;
TextView mNowClickView;
private boolean isSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
setResult(Activity.RESULT_CANCELED);
mFileListView = (ListView) findViewById(R.id.fileListView);
mBackBtn = (Button) findViewById(R.id.selectFileBackBtn);
mEnsureBtn = (Button) findViewById(R.id.selectFileEnsureBtn);
mCancelBtn = (Button) findViewById(R.id.selectFileCancelBtn);
sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
path = sdcardPath;
mAdapterManager = BluetoothApplication.getInstance().getAdapterManager();
mFileListView.setAdapter(mAdapterManager.getFileListAdapter());
mAdapterManager.updateFileListAdapter(path);
mFileListView.setOnItemClickListener(mFileListOnItemClickListener);
mBackBtn.setOnClickListener(mBackBtnClickListener);
mEnsureBtn.setOnClickListener(mEnsureBtnClickListener);
mCancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FileTranActivity.this.finish();
}
});
}
private OnItemClickListener mFileListOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
file = (File) mFileListView.getAdapter().getItem(position);
if(file.isFile()){
if(null != mLastClickView){
mLastClickView.setTextColor(Color.WHITE);
}
mNowClickView = (TextView) view.findViewById(R.id.fileNameTV);
mNowClickView.setTextColor(Color.BLUE);
isSelected = true;
mLastClickView = mNowClickView;
}else {
path = file.getAbsolutePath();
updateFileList();
}
}
};
private OnClickListener mBackBtnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(path.equals(sdcardPath)){
return ;
}
path = path.substring(0, path.lastIndexOf("/"));
updateFileList();
}
};
private OnClickListener mEnsureBtnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(!isSelected){
Toast.makeText(FileTranActivity.this, "请选择文件!", Toast.LENGTH_LONG).show();
return ;
}
Intent intent = new Intent();
intent.putExtra(BluetoothChat.SEND_FILE_NAME, file.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
FileTranActivity.this.finish();
}
};
private void updateFileList() {
if(null != mLastClickView){
mLastClickView.setTextColor(Color.WHITE);
mLastClickView = null;
isSelected = false;
}
if(null == updateFileListRunnable){
updateFileListRunnable = new Runnable() {
#Override
public void run() {
mAdapterManager.updateFileListAdapter(path);
}
};
}
if(null == mOtherHandler){
HandlerThread handlerThread = new HandlerThread("other_thread");
handlerThread.start();
mOtherHandler = new Handler(handlerThread.getLooper());
}
mOtherHandler.post(updateFileListRunnable);
}
}
then ,I find it point out the error in the FileTranActivity.java
mAdapterManager = BluetoothApplication.getInstance().getAdapterManager();
so ,here is BluetoothApplication.java
package com.example.android.BluetoothFileTran;
import com.example.android.BluetoothFileTran.adapter.AdapterManager;
import com.example.android.BluetoothFileTran.adapter.util.TouchObject;
import android.app.Application;
public class BluetoothApplication extends Application {
private static BluetoothApplication application;
private AdapterManager mAdapterManager;
private TouchObject mTouchObject;
#Override
public void onCreate() {
super.onCreate();
if(null == application){
application = this;
}
mTouchObject = new TouchObject();
}
public static BluetoothApplication getInstance(){
return application;
}
public AdapterManager getAdapterManager() {
return mAdapterManager;
}
public void setAdapterManager(AdapterManager adapterManager) {
this.mAdapterManager = adapterManager;
}
public TouchObject getTouchObject() {
return mTouchObject;
}
public void setTouchObject(TouchObject touchObject) {
this.mTouchObject = touchObject;
}
}
and AdapterManager.java
package com.example.android.BluetoothFileTran.adapter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothFileTran.adapter.FileListAdapter;
public class AdapterManager {
private Context mContext;
private FileListAdapter mFileListAdapter;
private List<BluetoothDevice> mDeviceList;
private List<File> mFileList;
private Handler mainHandler;
public AdapterManager(Context context){
this.mContext = context;
}
public FileListAdapter getFileListAdapter(){
if(null == mFileListAdapter){
mFileList = new ArrayList<File>();
mFileListAdapter = new FileListAdapter(mContext, mFileList, R.layout.file_list_item);
}
return mFileListAdapter;
}
public void clearDevice(){
if(null != mDeviceList){
mDeviceList.clear();
}
}
public void addDevice(BluetoothDevice bluetoothDevice){
mDeviceList.add(bluetoothDevice);
}
public void changeDevice(int listId, BluetoothDevice bluetoothDevice){
mDeviceList.remove(listId);
mDeviceList.add(listId, bluetoothDevice);
}
public void updateFileListAdapter(String path){
mFileList.clear();
mFileList.addAll(getFileList(path));
if(null == mainHandler){
mainHandler = new Handler(mContext.getMainLooper());
}
mainHandler.post(new Runnable() {
#Override
public void run() {
mFileListAdapter.notifyDataSetChanged();
}
});
}
public List<BluetoothDevice> getDeviceList() {
return mDeviceList;
}
public static List<File> getFileList(String path){
List<File> fileList = new ArrayList<File>();
File[] files = new File(path).listFiles();
if(files.length > 0){
List<File> allFolder = new ArrayList<File>();
List<File> allFile = new ArrayList<File>();
for(File file : files){
if(file.isFile()){
allFile.add(file);
}else {
allFolder.add(file);
}
}
fileList.addAll(allFolder);
fileList.addAll(allFile);
}
return fileList;
}
}
my xml is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.BluetoothChat"
android:versionCode="1"
android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools">
<uses-sdk
android:minSdkVersion="6"
android:targetSdkVersion="18" tools:ignore="OldTargetApi"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#drawable/ic_launcher"
android:theme="#style/AppTheme" >
<activity android:name="com.example.android.BluetoothChat.BluetoothChat"
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="com.example.android.BluetoothChat.DeviceListActivity"
android:label="#string/select_device"
android:theme="#android:style/Theme.Dialog"
/>
<activity android:name="com.example.android.BluetoothFileTran.FileTranActivity"
android:label="#string/select_file"
android:theme="#android:style/Theme.Dialog"
/>
</application>
</manifest>

Register in the AndroidManifest the BluetoothFileTran class as application name in application tag:
<application
android:allowBackup="true"
android:name="com.example.android.BluetoothFileTran"
...
Without this, the BluetoothFileTran will not be loaded, and onCreate will never invoked.
This will return a null reference in BluetoothApplication.getInstance(), which are causing your NullPointerException.
Reference
Notice: Your package in manifest, package="com.example.android.BluetoothChat" is different from the package that BluetoothFileTran is located (not in one of childs). I recommend you to use the package com.example.android instead of com.example.android.BluetoothChat in manifest tag.

Related

Error inflating class androidx.leanback.widget.BrowseFrameLayout

I'm testing the new support library leanback to design apps for TV, and i have a error ever android try to inflate the BrowseFragment and it throws this exception and don't know how to solve it. Thank you so much for your help.
Error -
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.directsportsnetwork.tv/com.directsportsnetwork.tv.ui.TeamSclActivity}: android.view.InflateException: Binary XML file line #67 in com.directsportsnetwork.tv:layout/activity_teamscl: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.view.InflateException: Binary XML file line #67 in com.directsportsnetwork.tv:layout/activity_teamscl: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: android.view.InflateException: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: android.view.InflateException: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Field.get(java.lang.Object)' on a null object reference
at uk.co.chrisjenx.calligraphy.ReflectionUtils.getValue(ReflectionUtils.java:29)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(CalligraphyLayoutInflater.java:203)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(CalligraphyLayoutInflater.java:20)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:302)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:237)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at androidx.leanback.app.BrowseFragment.onCreateView(BrowseFragment.java:1318)
at android.app.Fragment.performCreateView(Fragment.java:2505)
at android.app.FragmentManagerImpl.ensureInflatedFragmentView(FragmentManager.java:1491)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1274)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1486)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1728)
E/AndroidRuntime: at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3562)
at android.app.FragmentController.onCreateView(FragmentController.java:104)
at android.app.Activity.onCreateView(Activity.java:7112)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:229)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:303)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:237)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
at android.transition.Scene.enter(Scene.java:182)
at com.android.internal.policy.PhoneWindow.transitionTo(PhoneWindow.java:522)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:453)
at android.app.Activity.setContentView(Activity.java:3468)
at androidx.activity.ComponentActivity.setContentView(ComponentActivity.java:448)
at com.directsportsnetwork.tv.ui.TeamSclActivity.onCreate(TeamSclActivity.java:55)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
My Activity code is -
package com.directsportsnetwork.tv.ui;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.directsportsnetwork.tv.R;
import com.directsportsnetwork.tv.api.DeviceLogManager;
import com.directsportsnetwork.tv.api.Utils;
import org.json.JSONArray;
import java.util.HashMap;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class TeamSclActivity extends FragmentActivity {
private String TAG = TeamSclActivity.class.getSimpleName();
private ImageView topShelfImg, topShelfMask;
private TeamSclFragment mTeamSclFragment;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teamscl);
IntentFilter filter = new IntentFilter();
filter.addAction("com.directsportsnetwork.tv.STOP");
registerReceiver(broadcastReceiver, filter);
DeviceLogManager.instance().sendTeamSelectionPageData(TeamSclActivity.this);
topShelfImg = (ImageView) findViewById(R.id.top_shelf_image);
topShelfMask = (ImageView) findViewById(R.id.top_shelf_mask);
Intent intent = getIntent();
if (intent != null) {
try {
String channelData = intent.getStringExtra(Utils.EXTRA_CHANNEL_RESPONSE);
HashMap<String, Integer> teamTrnMap = (HashMap<String, Integer>) intent.getSerializableExtra(Utils.EXTRA_TEAM_TRN_MAP);
mTeamSclFragment = (TeamSclFragment) getFragmentManager().findFragmentById(R.id.main_browse_fragment);
mTeamSclFragment.onResponseData(new JSONArray(channelData), teamTrnMap);
} catch (Exception e) {
e.printStackTrace();
}
setTopShelfMask();
final Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
try {
mHandler.postDelayed(this, 300);
if (mTeamSclFragment.getView() != null && getCurrentFocus() instanceof RelativeLayout) {
mTeamSclFragment.getView().requestFocus();
mHandler.removeCallbacks(this);
mHandler.removeCallbacksAndMessages(null);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}, 300); //Changes START HERE FOR NEW CHANGES - 10/20/2018
}
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
#SuppressLint("MissingSuperCall")
#Override
protected void onSaveInstanceState(Bundle outState) {
//No call for super(). Bug on API Level > 11.
}
// remot Button OnClickListener methods
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
// Remove shadow over topShelfImage at here
if (mTeamSclFragment != null) {
mTeamSclFragment.startBackgroundTimer();
}
default:
return super.onKeyUp(keyCode, event);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP) {
// Add shadow over topShelfImage at here
topShelfImg.setAlpha(0.3f);
}
if (mTeamSclFragment != null) {
mTeamSclFragment.onMyKeyDown(keyCode, event);
}
return false;
}
public ImageView getTopShelfImg() {
return topShelfImg;
}
public void setTopShelfMask() {
if (Utils.SHOW_TOP_SHELF_MASK) {
topShelfMask.setBackground(ContextCompat.getDrawable(TeamSclActivity.this, R.drawable.ic_mask_bottom));
}
}
}
My Fragment code -
package com.directsportsnetwork.tv.ui;
import static androidx.leanback.app.BackgroundManager.getInstance;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.leanback.app.BackgroundManager;
import androidx.leanback.app.BrowseFragment;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlight;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import androidx.leanback.widget.ListRowPresenter;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.Row;
import androidx.leanback.widget.RowPresenter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.directsportsnetwork.tv.R;
import com.directsportsnetwork.tv.api.OnResponseReceived;
import com.directsportsnetwork.tv.api.TvApplication;
import com.directsportsnetwork.tv.api.Utils;
import com.directsportsnetwork.tv.model.Team;
import com.directsportsnetwork.tv.presenter.TeamPresenter;
import com.directsportsnetwork.tv.provider.DataBaseHelper;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class TeamSclFragment extends BrowseFragment implements OnResponseReceived {
private final String TAGS = "TeamSclFragment";
private final Handler mHandler = new Handler();
private Drawable mDefaultBackground;
private DisplayMetrics mMetrics;
private Timer mBackgroundTimer;
private URI mBackgroundURI;
private URI defaultBackgroundURI;
public Team selectedTeam;
private JSONArray teamData;
private HashMap<String, Integer> teamTrnMap;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private boolean isFavoriteDisable(String teamId) {
return !(teamTrnMap != null && teamTrnMap.get(teamId) != null);
}
private int getTrnByTeamId(String teamId) {
return teamTrnMap.get(teamId);
}
#Override
public void onResponseData(JSONArray data, HashMap<String, Integer> teamTrnMap) {
try {
Log.e(TAGS, "apiResponse: " + data);
teamData = data;
this.teamTrnMap = teamTrnMap;
prepareBackgroundManager();
setupUIElements();
// Set rows as per data fetched form API
loadTeamRows(teamData);
setupEventListeners();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (null != mBackgroundTimer) {
mBackgroundTimer.cancel();
}
}
#Override
public void onResume() {
super.onResume();
if (TvApplication.isFavChanged && teamData != null) {
loadTeamRows(teamData);
TvApplication.isFavChanged = false;
if (getView() != null) {
getView().requestFocus();
setSelectedPosition(0, true);
startBackgroundTimer();
}
}
}
#Override
public void onPause() {
super.onPause();
}
public void onMyKeyDown(int keyCode, KeyEvent event) {
//do whatever you want here
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
getActivity().finish();
getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
break;
}
}
private void loadTeamRows(JSONArray teamCategoryList) {
try {
ArrayList<Team> favTeamList = new ArrayList<>();
if (Utils.isStoragePermissionGranted(getActivity())) {
DataBaseHelper dataBase = DataBaseHelper.getInstance(getActivity());
favTeamList = dataBase.getAllFavorites();
} else {
favTeamList.add(null);
Utils.showToast(getActivity(), getResources().getString(R.string.no_storage_permission));
}
ListRowPresenter mListRowPresenter = new ListRowPresenter(FocusHighlight.ZOOM_FACTOR_NONE, true);
ArrayObjectAdapter mRowsAdapter = new ArrayObjectAdapter(mListRowPresenter);
TeamPresenter teamPresenter = new TeamPresenter();
for (int i = 0; i < teamCategoryList.length() + 1; i++) {
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(teamPresenter);
if (i == 0) {
// This is to create Favorite card row
for (int index = 0; index < favTeamList.size(); index++) {
if (favTeamList.get(index) == null) {
listRowAdapter.add(getResources().getString(R.string.favorites));
} else {
Team team = favTeamList.get(index);
team.setIsFavorite(1);
if (isFavoriteDisable(team.getId())) {
// TODO: Team is disabled, remove it from favorites
DataBaseHelper dataBase = DataBaseHelper.getInstance(getActivity());
dataBase.removeFavorite(team.getId());
TvApplication.isFavChanged = true;
continue;
} else {
team.setReleaseNo(getTrnByTeamId(team.getId()));
}
listRowAdapter.add(team);
}
}
HeaderItem header = new HeaderItem(i, "Favorites");
mRowsAdapter.add(new ListRow(header, listRowAdapter));
} else {
JSONArray teamList = teamCategoryList.getJSONObject(i - 1).getJSONArray("team");
String category = teamCategoryList.getJSONObject(i - 1).getString("name");
String categoryId = teamCategoryList.getJSONObject(i - 1).getString("id");
for (int index = 0; index < teamList.length(); index++) {
JSONObject teamObj = teamList.getJSONObject(index);
String id = teamObj.getString("id");
String name = teamObj.getString("name");
String shortdesc = teamObj.getString("shortdesc");
String longdesc = teamObj.getString("longdesc");
int trn = teamObj.getInt("trn");
//trn stands for Team Release Number
Team team = new Team();
team.setCatId(categoryId);
team.setCatName(category);
team.setId(id);
team.setName(name);
team.setShortdesc(shortdesc);
team.setLongdesc(longdesc);
team.setIsFavorite(0);
team.setReleaseNo(trn);
if (category.equalsIgnoreCase("NASCAR")) {
team.setIsNascar(1);
} else {
team.setIsNascar(0);
}
listRowAdapter.add(team);
}
HeaderItem header = new HeaderItem(i, category);
mRowsAdapter.add(new ListRow(header, listRowAdapter));
}
}
setAdapter(mRowsAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
private void prepareBackgroundManager() {
BackgroundManager mBackgroundManager = getInstance(getActivity());
mBackgroundManager.attach(getActivity().getWindow());
mDefaultBackground = ContextCompat.getDrawable(getActivity(), R.drawable.default_background);
mBackgroundManager.setColor(Color.BLACK);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
}
private void setupUIElements() {
getTitleView().setVisibility(View.GONE);
// To hide left side header for BrowseFragment
setHeadersState(HEADERS_DISABLED);
setHeadersTransitionOnBackEnabled(true);
}
private void setupEventListeners() {
setOnItemViewClickedListener(new ItemViewClickedListener());
setOnItemViewSelectedListener(new ItemViewSelectedListener());
}
protected void updateBackground(String uri) {
try {
int width = mMetrics.widthPixels;
int height = mMetrics.heightPixels;
final TeamSclActivity activity = ((TeamSclActivity) getActivity());
if (activity.getTopShelfImg().getDrawable().getConstantState() == getResources().getDrawable(R.drawable.ic_start).getConstantState() && (uri == defaultBackgroundURI.toString())) {
} else {
//start
if (activity != null) {
Glide.with(activity).load(uri).error(mDefaultBackground).placeholder(R.drawable.teamblank).into(new CustomTarget<Drawable>(width, height) {
#Override
public void onResourceReady(#NonNull Drawable resource, #Nullable Transition<? super Drawable> transition) {
activity.getTopShelfImg().setImageDrawable(resource);
Utils.crossfade(activity.getTopShelfImg());
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
}
//end
}
mBackgroundTimer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startBackgroundTimer() {
if (mBackgroundTimer != null) {
mBackgroundTimer.cancel();
}
mBackgroundTimer = new Timer();
mBackgroundTimer.schedule(new UpdateBackgroundTask(), Utils.BACKGROUND_UPDATE_DELAY);
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
#Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Team) {
Team team = (Team) item;
Intent intent = new Intent(getActivity(), TeamChnlActivity.class);
intent.putExtra(Utils.EXTRA_TEAM, team);
startActivity(intent);
} else if (item instanceof String) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getResources().getString(R.string.favorite_alert_msg));
builder.setCancelable(true);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
private final class ItemViewSelectedListener implements OnItemViewSelectedListener {
#Override
public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Team) {
Team team = ((Team) item);
try {
selectedTeam = team;
mBackgroundURI = new URI(team.getTopShelfImageUrl(team.getId(), team.getReleaseNo()));
defaultBackgroundURI = new URI(Utils.MEDIA_PREFIX_URL + "/tv/images/app/start.jpg?");
if (team.getIsFavorite() == 1) {
startBackgroundTimer();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (item instanceof String) {
try {
selectedTeam = null;
Random random = new Random();
mBackgroundURI = new URI(Utils.MEDIA_PREFIX_URL + "/tv/images/app/start.jpg?" + random.nextInt(100));
defaultBackgroundURI = mBackgroundURI;
startBackgroundTimer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private class UpdateBackgroundTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
if (mBackgroundURI != null) {
updateBackground(mBackgroundURI.toString());
}
}
});
}
}
}
My activity_teamscl.xml code -
<?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">
<fragment
android:id="#+id/main_browse_fragment"
android:name="com.directsportsnetwork.tv.ui.TeamSclFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignTop="#+id/center_baseline"
tools:context=".ui.TeamSclActivity"
tools:deviceIds="tv"
tools:ignore="MergeRootFrame" />
</RelativeLayout>

How to call another activity by menuitem? Android Studio Error: method call expected

I am completely new to Android Studio and just learned Object-oriented programming. My project requires me to build something on open-source code. I added a new menu item to a menu and want to start another activity once the user clicks the menu item with id: plot. I followed a recipe on the internet but got an error with it. It said 'method call expected' which means Terminal Fragment may be a method. I got confused, as I thought it is a class(an activity). Could anyone give me instructions to start an activity (turn to the next page with a different activity) in this case? What will be the simplest way to do this? Much Appreciated.
I added this in onOptionsItemSelected(MenuItem item).
if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}
TerminalFragment.java (entire code)
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
/*
* Lifecycle
*/
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
#Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
#Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
#SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
#Override
public void onAttach(#NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
#Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
#Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
#Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
#Override
public void onSerialRead(byte[] data) {
receive(data);
}
#Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
menu_terminal.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/plot"
android:title="PLOTDATA"
app:showAsAction="always" />
<item
android:id="#+id/clear"
android:icon="#drawable/ic_delete_white_24dp"
android:title="Clear"
app:showAsAction="always" />
<item
android:id="#+id/newline"
android:title="Newline"
app:showAsAction="never" />
<item
android:id="#+id/hex"
android:title="HEX Mode"
android:checkable="true"
app:showAsAction="never" />
</menu>
Here, TerminalFragment is a fragment, not an activity. And so, instead of using TerminalFragment.this in new Intent(), you should use getActivity().
So, the final code would look something like this:
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
You can also check this: Intent from Fragment to Activity

how to call onOptionsItemSelected on a different activity

I have an activity with uses onOptionsItemSelected(MenuItem item) method in FolderActivity and I want to call this method on another activity (MainActivity)
the main activity uses CMU Sphinx - Speech Recognition Toolkit.
I need to call some methods from FolderActivity to MainActivity.
package com.evolution.filemanager.folders;
import static android.widget.Toast.makeText;
import java.io.File;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.evolution.filemanager.FileManagerApplication;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.clipboard.Clipboard;
import com.evolution.filemanager.clipboard.Clipboard.ClipboardListener;
import com.evolution.filemanager.clipboard.ClipboardFileAdapter;
import com.evolution.filemanager.favourites.FavouritesManager;
import com.evolution.filemanager.favourites.FavouritesManager.FavouritesListener;
import com.evolution.filemanager.nav_drawer.NavDrawerAdapter;
import com.evolution.utils.FontApplicator;
import com.evolution.utils.ListViewUtils;
import edu.cmu.pocketsphinx.demo.R;
public class FolderActivity extends Activity implements OnItemClickListener, ClipboardListener, FavouritesListener
{
public static class FolderNotOpenException extends Exception
{
}
private static final String LOG_TAG = "Main Activity";
public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
File lastFolder=null;
private FontApplicator fontApplicator;
public static Activity FOLDERACTIVITY;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_folder);
setupDrawers();
Clipboard.getInstance().addListener(this);
FOLDERACTIVITY = this;
fontApplicator = new FontApplicator(getApplicationContext(), "Roboto_Light.ttf").applyFont(getWindow().getDecorView());
}
public FontApplicator getFontApplicator()
{
return fontApplicator;
}
#Override
protected void onDestroy()
{
Clipboard.getInstance().removeListener(this);
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getFavouritesManager().removeFavouritesListener(this);
super.onDestroy();
}
public void setLastFolder(File lastFolder)
{
this.lastFolder = lastFolder;
}
#Override
protected void onPause()
{
if (lastFolder != null)
{
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
}
super.onPause();
}
public void setActionbarVisible(boolean visible)
{
ActionBar actionBar = getActionBar();
if (actionBar == null) return;
if (visible)
{
actionBar.show();
setSystemBarTranslucency(false);
}
else
{
actionBar.hide();
setSystemBarTranslucency(true);
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
protected void setSystemBarTranslucency(boolean translucent)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
if (translucent)
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
else
{
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags &= (~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setAttributes(params);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
public void setupDrawers()
{
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
{
boolean actionBarShown = false;
#Override
public void onDrawerOpened(View drawerView)
{
makeText(getApplicationContext(), "drawer open", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(drawerView);
setActionbarVisible(true);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView)
{
makeText(getApplicationContext(), "drawer close", Toast.LENGTH_SHORT).show();
actionBarShown=false;
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0 && actionBarShown == false)
{
actionBarShown = true;
setActionbarVisible(true);
}
else if (slideOffset <= 0) actionBarShown = false;
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
drawerLayout.setFocusableInTouchMode(false);
// drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setupNavDrawer();
setupClipboardDrawer();
}
#Override
public void onBackPressed()
{
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else if (drawerLayout.isDrawerOpen(GravityCompat.END))
drawerLayout.closeDrawer(GravityCompat.END);
else
super.onBackPressed();
}
void setupNavDrawer()
{
FileManagerApplication application = (FileManagerApplication) getApplication();
// add listview header to push items below the actionbar
ListView navListView = (ListView) findViewById(R.id.listNavigation);
ListViewUtils.addListViewPadding(navListView, this, true);
loadFavourites(application.getFavouritesManager());
application.getFavouritesManager().addFavouritesListener(this);
}
void setupClipboardDrawer()
{
// add listview header to push items below the actionbar
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
ListViewUtils.addListViewHeader(clipboardListView, this);
onClipboardContentsChange(Clipboard.getInstance());
}
void loadFavourites(FavouritesManager favouritesManager)
{
ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
NavDrawerAdapter navDrawerAdapter = new NavDrawerAdapter(this, new ArrayList<NavDrawerAdapter.NavDrawerItem>(favouritesManager.getFolders()));
navDrawerAdapter.setFontApplicator(fontApplicator);
listNavigation.setAdapter(navDrawerAdapter);
listNavigation.setOnItemClickListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
if (getFragmentManager().findFragmentById(R.id.fragment) == null)
{
FolderFragment folderFragment = new FolderFragment();
if (getIntent().hasExtra(EXTRA_DIR))
{
Bundle args = new Bundle();
args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
folderFragment.setArguments(args);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, folderFragment)
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
makeText(getApplicationContext(), "unsa ni?", Toast.LENGTH_SHORT).show();
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
if (actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId())
{
case R.id.menu_about:
startActivity(new Intent(getApplicationContext(), AboutActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFragment(Fragment fragment)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment, fragment)
.commit();
}
public void goBack()
{
getFragmentManager().popBackStack();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public FolderFragment getFolderFragment()
{
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment);
if (fragment instanceof FolderFragment)
return (FolderFragment) fragment;
else return null;
}
public File getCurrentFolder() throws FolderNotOpenException
{
FolderFragment folderFragment = getFolderFragment();
if (folderFragment == null)
throw new FolderNotOpenException();
else return folderFragment.currentDir;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch (arg0.getId())
{
case R.id.listNavigation:
NavDrawerAdapter.NavDrawerItem item = (NavDrawerAdapter.NavDrawerItem) arg0.getItemAtPosition(arg2);
if (item.onClicked(this))
drawerLayout.closeDrawers();
break;
case R.id.listClipboard:
FolderFragment folderFragment = getFolderFragment();
if (folderFragment != null)
{
// TODO: paste single file
}
break;
default:
break;
}
}
public File getLastFolder()
{
return lastFolder;
}
#Override
public void onClipboardContentsChange(Clipboard clipboard)
{
invalidateOptionsMenu();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
if (clipboard.isEmpty() && drawerLayout != null)
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
else
{
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
FileManagerApplication application = (FileManagerApplication) getApplication();
if (clipboardListView != null)
{
ClipboardFileAdapter clipboardFileAdapter = new ClipboardFileAdapter(this, clipboard, application.getFileIconResolver());
clipboardFileAdapter.setFontApplicator(fontApplicator);
clipboardListView.setAdapter(clipboardFileAdapter);
}
}
}
#Override
public void onFavouritesChanged(FavouritesManager favouritesManager)
{
loadFavourites(favouritesManager);
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event)
{
Log.d("Key Long Press", event.toString());
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
return true;
}
else return super.onKeyLongPress(keyCode, event);
}
}
and the activity where I want to call
package edu.cmu.pocketsphinx.demo;
import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.folders.FolderActivity;
import com.evolution.utils.DataClearer;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;
public class MainActivity extends Activity implements
RecognitionListener {
public AnimationDrawable rocketAnimation;
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "digits";
private static final String MENU_SEARCH = "menu";
private static final String KEYPHRASE = "frost";
private static final String GO_BACK = "back";
private static final String PREVIOUS = "previous";
private static final String OPEN_FILE_MANAGER = "open file manager";
private static final String OPEN_ABOUT = "open about";
private static final String OPEN_MUSIC = "open music";
private static final String OPEN_PICTURES = "open pictures";
private static final String OPEN_VIDEOS = "open videos";
private static final String SHOW_COMMANDS = "show commands";
private static final String CLOSE_FILE_MANAGER = "close file manager";
private static final String CLOSE_ABOUT = "close about";
private static final String CLOSE_MUSIC = "close music";
private static final String CLOSE_PICTURES = "close pictures";
private static final String CLOSE_VIDEOS = "close videos";
private static final String CLOSE_COMMANDS = "close commands";
private static final String SHOW_DRAWER = "show drawer";
private static final String HIDE_DRAWER = "hide drawer";
public static boolean isOPEN_FILE_MANAGER = false;
private static boolean isOPEN_ABOUT = false;
private static boolean isOPEN_MUSIC = false;
private static boolean isOPEN_PICTURES = false;
private static boolean isOPEN_VIDEOS = false;
private static boolean isSHOW_COMMANDS = false;
private static boolean isSHOW_DRAWER = false;
private static String MENU_CAPTION;
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Prepare the data for UI
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
captions.put(DIGITS_SEARCH, R.string.digits_caption);
captions.put(FORECAST_SEARCH, R.string.forecast_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
ImageView rocketImage = (ImageView) findViewById(R.id.imageViewAnim);
rocketImage.setBackgroundResource(R.drawable.heart_animation);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
TextView tv = ((TextView) findViewById(R.id.caption_text));
if (text.equals(KEYPHRASE))
{
switchSearch(MENU_SEARCH);
rocketAnimation.start();
}
else if (text.equals(OPEN_FILE_MANAGER))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , FolderActivity.class);
startActivity(intent);
isOPEN_FILE_MANAGER = true;
}
else if (text.equals(CLOSE_FILE_MANAGER))
{
if(isOPEN_FILE_MANAGER == true)
{
switchSearch(KWS_SEARCH);
FolderActivity.FOLDERACTIVITY.finish();
isOPEN_FILE_MANAGER = false;
}
}
else if (text.equals(SHOW_COMMANDS))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , Commands.class);
startActivity(intent);
isSHOW_COMMANDS = true;
}
else if (text.equals(CLOSE_COMMANDS))
{
if(isSHOW_COMMANDS == true)
{
switchSearch(KWS_SEARCH);
Commands.SHOWCOMMANDS.finish();
}
}
else if (text.equals(OPEN_PICTURES))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , AboutActivity.class);
startActivity(intent);
}
else if(text.equals(OPEN_ABOUT))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent(PocketSphinxActivity.this, AboutActivity.class);
startActivity(intent);
isOPEN_ABOUT = true;
}
else if(text.equals(CLOSE_ABOUT))
{
if (isOPEN_ABOUT == true)
{
switchSearch(KWS_SEARCH);
AboutActivity.ABOUTACTIVITY.finish();
}
}
else if(text.equals(GO_BACK) || text.equals(PREVIOUS))
{
if(isOPEN_FILE_MANAGER == true )
{
FolderActivity.FOLDERACTIVITY//where i want to call onOptionsItemSelected
switchSearch(KWS_SEARCH);
}
}
else
{
switchSearch(KWS_SEARCH);
((TextView) findViewById(R.id.result_text)).setText(text);
}
}
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
if (DIGITS_SEARCH.equals(recognizer.getSearchName())
|| FORECAST_SEARCH.equals(recognizer.getSearchName())
|| OPEN_FILE_MANAGER.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create grammar-based searches.
File menuGrammar = new File(modelsDir, "grammar/menu.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this); //clear cache to minimize the app size
DataClearer.getInstance().clearApplicationData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
the FolderActivity runs on top of the MainActivty but the voice recognition in MainActivity is still active and I want the voice itself do some manipulation in the FolderActivity
Here's a few suggestions:
Have FolderActivity register a BroadcastReceiver as a listener for a certain Intent. When MainActivity wants to do something in FolderActivity, it can send a broadcast Intent which will be seen by the BroadcastReceiver in FolderActivity, which can then call the appropriate method in the `Activity.
When MainActivity wants to do something in FolderActivity, it can launch FolderActivity again using an Intent with flag Intent.FLAG_ACTIVITY_SINGLE_TOP and some "extra" that describes what FolderActivity should do. In FolderActivity override onNewIntent(), read the passed Intent parameter and use it to determine what method to call in FolderActivity. Because the Activity was launched withIntent.FLAG_ACTIVITY_SINGLE_TOP, Android won't create a new instance of the Activity, it will just callonNewIntent()` on the existing instance.
Have FolderActivity set a public static variable of type Activity to a reference to itself in onCreate(). MainActivity can then call a method on FolderActivity by doing something like FolderActivity.activityReference.doSomething()
Method 3 is not the preferred method, since you need to make sure that you set the public static variable to null in FolderActivity.onDestroy() and there are other concerns (timing issues, memory leaks, etc.) that need to be dealt with properly.
NOTE: You probably don't want to call onOptionsItemSelected() directly. This method is called by the Android framework when an options item is selected by the user. You should call directly the method that actually does something, not this framework callback method.

Unable to start activity ComponentInfo{MainFrag}: java.lang.NullPointerException

Hello I'm working on an application that is going to be android launcher there are three different screens in this launcher the first screen is a bookshelf that is supposed to import and Show all books in the SD card place on the device the second is a calculator (works just fine!) Third is a Homework page where you can make google drive docs and flashcards (also works fine!!) I get no errors when I run my code the app automatically crashes when it launches on my device and on the emulator.
Heres my Logcat:
11-23 15:05:06.314: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:05:15.084: E/Trace(3807): error opening trace file: No such file or directory (2)
11-23 15:05:15.254: E/AndroidRuntime(3807): FATAL EXCEPTION: main
11-23 15:05:15.254: E/AndroidRuntime(3807): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.d4a.tobias/it.gmariotti.android.examples.googleaccount.MainFrag}: java.lang.NullPointerException
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.os.Looper.loop(Looper.java:137)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-23 15:05:15.254: E/AndroidRuntime(3807): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 15:05:15.254: E/AndroidRuntime(3807): at java.lang.reflect.Method.invoke(Method.java:511)
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-23 15:05:15.254: E/AndroidRuntime(3807): at dalvik.system.NativeStart.main(Native Method)
11-23 15:05:15.254: E/AndroidRuntime(3807): Caused by: java.lang.NullPointerException
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.sibext.android_shelf.adapter.ShelfAdapter.setToListView(ShelfAdapter.java:70)
11-23 15:05:15.254: E/AndroidRuntime(3807): at it.gmariotti.android.examples.googleaccount.MainFrag.onCreate(MainFrag.java:78)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.Activity.performCreate(Activity.java:5104)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
11-23 15:05:15.254: E/AndroidRuntime(3807): ... 11 more
11-23 15:05:15.354: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:05:15.824: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:07:05.354: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
Heres MainFrag.java:
package it.gmariotti.android.examples.googleaccount;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;
import com.d4a.tobias.R;
import com.sibext.android_shelf.ImportBooks;
import com.sibext.android_shelf.adapter.ShelfAdapter;
public class MainFrag extends FragmentActivity{
private MyAdapter mAdapter;
private ViewPager mPager;
//Shelf
private static final String TARGET_DIRECTORY = "mnt/sdcard/shelf/";
private ListView list;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainfrag);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
// TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles);
// titleIndicator.setViewPager(mPager);
// pts=(PagerTitleStrip)findViewById(R.id.pager_title_strip);
//Shelf
File dir = new File(TARGET_DIRECTORY);
if(!dir.exists()){
dir.mkdirs();
//past here
addBooksFromAssetsToCard();
}else{
String files[] = dir.list();
if(files.length == 0){
//past here
addBooksFromAssetsToCard();
}
}
list = (ListView)findViewById(R.id.list);
ShelfAdapter adapter = new ShelfAdapter(this, TARGET_DIRECTORY);
adapter.setToListView(list);
}
public static class MyAdapter extends FragmentPagerAdapter {
String arr[]={"Calculator","Books","Homework"};
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return arr[position];
}
#Override
public int getCount() {
return arr.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Calculator();
case 1:
return new Book();
case 2:
return new Homework();
default:
return null;
}
}
}
//Shelf
public void addBooksFromAssetsToCard(){
List<String> books;
try {
books = getBooksFromAsset(getApplicationContext());
for(String book : books){
copyFromAssets(book);
}
} catch (Exception e) {
}
}
public List<String> getBooksFromAsset(Context ctx) throws Exception
{
AssetManager assetManager =ctx.getAssets();
String[] files = assetManager.list("books");
List<String> it=Arrays.asList(files);
return it;
}
public void copyFromAssets(String book)
{
AssetManager assetManager = getAssets();
String[] files = null;
InputStream in = null;
OutputStream out = null;
//String filename = "filename.ext";
try
{
in = assetManager.open("books/"+book);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+"/shelf/"+book);
Log.d("Copying...", ""+book);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
Log.e("tag", "Failed to copy asset file: " + book, e);
}
}
public void copyFile(InputStream in, OutputStream out) throws Exception
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
Log.d("Copy_State", "Done...");
}
public void onImportClicked(View v){
Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent in = new Intent(getApplicationContext(), ImportBooks.class);
startActivity(in);
}
}
EDIT ADDED Shelf Adapter.java :
package com.sibext.android_shelf.adapter;
import java.io.File;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;
import com.d4a.tobias.R;
import com.sibext.android_shelf.MainActivity;
import com.sibext.android_shelf.shelf.ShelfItem;
public class ShelfAdapter extends BaseAdapter {
private static final int ROW_COUNT_DEFAULT = 2;
private static final int ROW_COUNT_LAND_DEFAULT = 4;
private static final int ROW_HEIGHT_DEFAULT = 150;
private Context context;
private int rowCount = ROW_COUNT_DEFAULT;
private int rowCountLand = ROW_COUNT_LAND_DEFAULT;
private int rowHeight = ROW_HEIGHT_DEFAULT;
private SparseArray<LoadPreviewTask> taskPool;
private ArrayList<ShelfItem> items;
String PATH;
ShelfItem item;
public ShelfAdapter(Context context, String targetDir) {
this.context = context;
items = new ArrayList<ShelfItem>();
taskPool = new SparseArray<ShelfAdapter.LoadPreviewTask>();
if (targetDir == null || context == null) {
throw new NullPointerException("ShelfAdapter: wrong paramenters - " +
(targetDir == null ? "Target directory " : "Context ") + "is null");
}
File dir = new File(targetDir);
if(dir.exists() && dir.isDirectory()){
for(File f : dir.listFiles()){
if(f != null && f.getName().endsWith(".pdf")){
items.add(new ShelfItem(f));
}
}
}
}
public void setToListView(ListView list){
list.setDividerHeight(0);
list.setAdapter(this);
}
public void setRowCount(int rowCount, int rowCountLand) {
this.rowCount = rowCount;
this.rowCountLand = rowCountLand;
}
public void setRowHeight(int rowHeight) {
this.rowHeight = rowHeight;
}
#Override
public int getCount() {
int sub = getSubItemsCount();
return (int)(sub/getRowCount()) + (sub%getRowCount() == 0 ? 0 : 1);
}
public int getSubItemsCount(){
return items.size();
}
#Override
public ShelfItem getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = View.inflate(context, R.layout.shelf_row, null);
AbsListView.LayoutParams itemParams = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT, rowHeight);
convertView.setLayoutParams(itemParams);
LinearLayout.LayoutParams subItemParams = getSubViewParams();
for(int i = 0; i < getRowCount(); i++){
View sub = getSubView(getSubPosition(position, i), null);
sub.setLayoutParams(subItemParams);
((ViewGroup)convertView).addView(sub);
holder.subViews.add(sub);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
for(int i = 0; i < holder.subViews.size(); i++){
getSubView(getSubPosition(position, i), holder.subViews.get(i));
}
}
return convertView;
}
public View getSubView(final int position, View convertView){
final SubViewHolder holder;
if(convertView == null){
convertView = View.inflate(context, R.layout.shelf_item, null);
holder = new SubViewHolder();
holder.img = (ImageView)convertView.findViewById(R.id.shelf_item_image);
convertView.setTag(holder);
} else {
holder = (SubViewHolder)convertView.getTag();
}
if(position >= getSubItemsCount()){
holder.img.setImageBitmap(null);
return convertView;
}
item = getItem(position);
PATH = item.getFile().getAbsolutePath();
Bitmap preview = item.getPreviewFromSD();
if(preview != null){
holder.img.setImageBitmap(preview);
} else {
holder.img.setImageResource(R.drawable.ic_launcher);
LoadPreviewTask task = taskPool.get(holder.hashCode());
if (task != null) {
task.cancel(true);
taskPool.remove(holder.hashCode());
task = null;
}
task = new LoadPreviewTask(holder, rowHeight);
taskPool.put(holder.hashCode(), task);
task.execute(item);
}
holder.img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ShelfItem si = items.get(position);
/*Toast.makeText(context, "Item #" + position+"\n"+si.getFile().getAbsolutePath(), Toast.LENGTH_SHORT).show();
*/
final CharSequence[] items = {"View", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Please choose:");
builder.setItems(items, new DialogInterface.OnClickListener() {
//Toast.makeText(getApplicationContext(), ""+items[0], Toast.LENGTH_SHORT).show();
public void onClick(DialogInterface dialog, int index) {
if(index == 0){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(si.getFile()),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}else if(index == 1){
File file = new File(si.getFile().getAbsoluteFile().toString());
boolean deleteStatus = file.delete();
if(deleteStatus){
Toast.makeText(context, "Deleted Successfully...", Toast.LENGTH_SHORT).show();
Intent in = new Intent(context, MainActivity.class);
context.startActivity(in);
}else{
Toast.makeText(context, "Unable to delete...", Toast.LENGTH_SHORT).show();
}
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
private int getSubPosition(int listItemPosition, int offset){
return listItemPosition * getRowCount() + offset;
}
private LinearLayout.LayoutParams getSubViewParams(){
LinearLayout.LayoutParams p = new LayoutParams(0, LayoutParams.MATCH_PARENT);
p.weight = 1f;
return p;
}
private int getRowCount() {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
? rowCount : rowCountLand;
}
private static class ViewHolder{
public ArrayList<View> subViews;
public ViewHolder() {
this.subViews = new ArrayList<View>();
}
}
private static class SubViewHolder{
public ImageView img;
}
private class LoadPreviewTask extends AsyncTask<ShelfItem, Void, Bitmap>{
private SubViewHolder holder;
private int rowHeight;
public LoadPreviewTask(SubViewHolder holder, int rowHeight) {
super();
this.holder = holder;
this.rowHeight = rowHeight;
}
#Override
protected Bitmap doInBackground(ShelfItem... params) {
ShelfItem item = (ShelfItem)params[0];
Bitmap preview = item.getPreview(rowHeight);
item.savePreview(preview);
return preview;
}
#Override
protected void onPostExecute(final Bitmap result) {
if(isCancelled()){
holder = null;
return;
}
holder.img.setImageBitmap(result);
taskPool.remove(holder.hashCode());
}
}
}
I'm still fairly new to Android so please don’t judge and any help will be greatly appreciated
Thanks in advance
list = (ListView)findViewById(R.id.list); returns null because your list is not created yet. Override the onViewCreated() and put your code in there.
Your problem is here: adapter.setToListView(list); should be something like: list.setAdapter(...) but you have another errors on ShelfAdapter.java, can you copy what you have written from line 65 to line 70?

Android App crash: FATAL EXCEPTION: main

I wrote Android QuizApp which randomly generates questions for users and then displays the result. When I tried to implement user interface where a user would enter the number and difficulty of questions, application started to crash and give me fatal exceptions. I have 4 classes:
package com.example.quizapp;
import java.util.Random;
public class Quiz {
private int difficulty;
private int numberOfQuestions;
private Question[] questions;
public Quiz(String difficulty, int numberOfQuestions) {
setDifficulty(difficulty);
this.numberOfQuestions = numberOfQuestions;
this.questions = new Question[this.numberOfQuestions];
for (int i = 0; i < this.numberOfQuestions; i++) {
this.questions[i] = new Question(this.difficulty);
}
}
public void setDifficulty(String difficulty) {
if (difficulty == "easy") {
this.difficulty = 1;
} else if (difficulty == "medium"){
this.difficulty = 2;
} else if (difficulty == "hard"){
this.difficulty = 3;
} else {
this.difficulty = -1;
}
}
public String getDifficulty() {
switch (difficulty) {
case 1:
return "easy";
case 2:
return "medium";
case 3:
return "hard";
default:
return "Difficulty not set correctly";
}
}
public Question getQuestionInstance(int number) {
return this.questions[number];
}
public String getQuestion(int number) {
return this.questions[number].QUESTION;
}
public int getOptionA(int number) {
return this.questions[number].OPTA;
}
public int getOptionB(int number) {
return this.questions[number].OPTB;
}
public int getOptionC(int number) {
return this.questions[number].OPTC;
}
public int getAnswer(int number) {
return this.questions[number].ANSWER;
}
class Question {
private int firstNumber;
private int secondNumber;
private char sign;
private String QUESTION;
private int OPTA;
private int OPTB;
private int OPTC;
private int ANSWER;
private int difficulty;
private Random rand;
public Question(int difficulty) {
this.difficulty = difficulty;
this.rand = new Random();
this.firstNumber = getRandomNumber();
this.secondNumber = getRandomNumber();
this.sign = getRandomSign();
this.ANSWER = calculateAnswer();
initializeOptions();
this.QUESTION = this.firstNumber + " " + this.sign + " " + this.secondNumber + " = ";
}
public String getQuestion() {
return this.QUESTION;
}
public int getOptionA() {
return this.OPTA;
}
public int getOptionB() {
return this.OPTB;
}
public int getOptionC() {
return this.OPTC;
}
public int getAnswer() {
return this.ANSWER;
}
private void initializeOptions() {
int number = this.rand.nextInt(3) + 1;
switch (number) {
case 1:
this.OPTA = this.ANSWER;
this.OPTB = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTC = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
break;
case 2:
this.OPTA = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTB = this.ANSWER;
this.OPTC = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
break;
case 3:
this.OPTA = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTB = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTC = this.ANSWER;
break;
}
}
private int calculateAnswer() {
int answer = 0;
switch (this.sign) {
case '+':
answer = this.firstNumber + this.secondNumber;
break;
case '-':
answer = this.firstNumber - this.secondNumber;
break;
case '*':
answer = this.firstNumber * this.secondNumber;
break;
case '/':
answer = this.firstNumber / this.secondNumber;
break;
}
return answer;
}
private int getRandomNumber() {
int number;
if (this.difficulty == 1) {
//number = 1 + Math.random()*100;
number = this.rand.nextInt(100) + 1;
} else if (this.difficulty == 2) {
//number = 1 + Math.random()*1000;
number = this.rand.nextInt(1000) + 1;
} else {
//number = 1 + Math.random()*1000;
number = this.rand.nextInt(1000) + 1;
}
return number;
}
private char getRandomSign() {
int number;
char sign;
//easy
if (this.difficulty == 1) {
number = this.rand.nextInt(2) + 1;
sign = convertNumberToSign(number);
//medium
} else if (this.difficulty == 2) {
if (this.firstNumber > 10 && this.secondNumber > 10) {
number = this.rand.nextInt(2) + 1;
sign = convertNumberToSign(number);
} else {
number = this.rand.nextInt(3) + 1;
sign = convertNumberToSign(number);
}
//hard
} else {
if (this.firstNumber / this.secondNumber == (int) (this.firstNumber / this.secondNumber)) {
number = this.rand.nextInt(4) + 1;
sign = convertNumberToSign(number);
} else {
number = this.rand.nextInt(3) + 1;
sign = convertNumberToSign(number);
}
}
return sign;
}
private char convertNumberToSign(int number) {
if (number == 1) {
return '+';
} else if (number == 2) {
return '-';
} else if (number == 3) {
return '*';
} else {
return '/';
}
}
}
}
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class QuizActivity extends Activity
{
Quiz quiz;
RadioButton rb1, rb2, rb3, rb4, rb5, rb6;
Button buttonOK;
String ans;
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
rb1=(RadioButton)findViewById(R.id.radio3);
rb2=(RadioButton)findViewById(R.id.radio4);
rb3=(RadioButton)findViewById(R.id.radio5);
rb4=(RadioButton)findViewById(R.id.radio6);
rb5=(RadioButton)findViewById(R.id.radio7);
rb6=(RadioButton)findViewById(R.id.radio8);
buttonOK=(Button)findViewById(R.id.button2);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup group2=(RadioGroup)findViewById(R.id.radioGroup3);
RadioButton answer2=(RadioButton)findViewById(group2.getCheckedRadioButtonId());
if (answer2.equals(rb4))
{
num = 5;
}
else if (answer2.equals(rb5))
{
num = 10;
}
else
{
num = 15;
}
RadioGroup group1=(RadioGroup)findViewById(R.id.radioGroup2);
RadioButton answer1=(RadioButton)findViewById(group1.getCheckedRadioButtonId());
if (answer1.equals(rb1))
{
ans = "easy";
}
else if (answer1.equals(rb2))
{
ans = "medium";
}
else
{
ans = "hard";
}
}
});
Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
intent.putExtra("answer", ans);
intent.putExtra("question", num);
QuizActivity.this.startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ui, menu);
return true;
}
}
package com.example.quizapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuestActivity extends Activity
{
Quiz quiz;
int score = 0;
int qid = 0;
Quiz.Question currentQuest;
TextView textQuestion;
RadioButton rba, rbb, rbc;
Button buttonNext;
String answer = null;
int numOfQuestion = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
Intent intent= getIntent();
if (intent != null)
{
answer=intent.getStringExtra("answer");
numOfQuestion=intent.getIntExtra("question", 0);
}
quiz= new Quiz(answer,numOfQuestion);
currentQuest=quiz.getQuestionInstance(qid);
textQuestion=(TextView)findViewById(R.id.textView1);
rba=(RadioButton)findViewById(R.id.radio0);
rbb=(RadioButton)findViewById(R.id.radio1);
rbc=(RadioButton)findViewById(R.id.radio2);
buttonNext=(Button)findViewById(R.id.button1);
setQuestionView();
buttonNext.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
RadioGroup group=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(group.getCheckedRadioButtonId());
Log.d("yourans", currentQuest.getAnswer() + " " + answer.getText());
if(Integer.toString(currentQuest.getAnswer()).equals(answer.getText()) )
{
score++;
Log.d("score", "Your score" + score);
}
if(qid<numOfQuestion)
{
currentQuest=quiz.getQuestionInstance(qid);
setQuestionView();
}else
{
Intent intent = new Intent(QuestActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}
private void setQuestionView()
{
textQuestion.setText(currentQuest.getQuestion());
rba.setText(Integer.toString(currentQuest.getOptionA()));
rbb.setText(Integer.toString(currentQuest.getOptionB()));
rbc.setText(Integer.toString(currentQuest.getOptionC()));
qid++;
}
}
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RatingBar;
import android.widget.TextView;
public class ResultActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
//access rating bar
RatingBar rbar=(RatingBar)findViewById(R.id.ratingBar1);
rbar.setNumStars(5);
rbar.setStepSize(0.5f);
TextView t=(TextView)findViewById(R.id.textResult);
//get and display the score
Bundle b = getIntent().getExtras();
int score= b.getInt("score");
rbar.setRating(score);
switch (score)
{
case 1:
case 2: t.setText("Better Luck Next Time!");
break;
case 3:
case 4:t.setText("Quite average");
break;
case 5:t.setText("Congratulations !");
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
}
Edited: I added AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quizapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.quizapp.QuizActivity"
android:label="#string/quiz_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.quizapp.QuestActivity"
android:label="#string/title_activity_quiz" >
</activity>
<activity
android:name="com.example.quizapp.ResultActivity"
android:label="#string/title_activity_result" >
</activity>
</application>
</manifest>
Edited: Updated application as suggested, this error pops up and app crashes:
10-23 10:10:32.368: E/AndroidRuntime(827): FATAL EXCEPTION: main
10-23 10:10:32.368: E/AndroidRuntime(827): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.QuestActivity}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.os.Looper.loop(Looper.java:137)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-23 10:10:32.368: E/AndroidRuntime(827): at java.lang.reflect.Method.invokeNative(Native Method)
10-23 10:10:32.368: E/AndroidRuntime(827): at java.lang.reflect.Method.invoke(Method.java:525)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-23 10:10:32.368: E/AndroidRuntime(827): at dalvik.system.NativeStart.main(Native Method)
10-23 10:10:32.368: E/AndroidRuntime(827): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
10-23 10:10:32.368: E/AndroidRuntime(827): at com.example.quizapp.Quiz.getQuestionInstance(Quiz.java:45)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.example.quizapp.QuestActivity.onCreate(QuestActivity.java:52)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.Activity.performCreate(Activity.java:5133)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-23 10:10:32.368: E/AndroidRuntime(827): ... 11 more
check this in manifest:
android:name="com.example.quizapp.QuizApp"
Have you this activity "QuizApp"?
change in manifest to:
android:name="com.example.quizapp.QuizActivity"
HTH.
You told Android that you have an Activity named QuizApp as your Main Activity, by saying
<activity
android:name="com.example.quizapp.QuizApp"
android:label="#string/quiz_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
but you never implemented it. Android looks for that activity in the package, com.example.quizapp, but it fails to find it, as we can see from the ClassNotFoundException in the LogCat messages,
10-21 06:31:26.907: E/AndroidRuntime(816): ... java.lang.ClassNotFoundException: Didn't find class "com.example.quizapp.QuizApp"...
You must implement your QuizApp Activity.
Its look like you have package name mismatch error in Manifest file. Correct it as
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quizapp"
...
</manifest>
And don't forget, you can specify the fully qualified name for each Activity
i.e.
<activity
android:name="com.example.quizapp.Activity_name"
...>
</activity>
Edit As per Requirement
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class QuizActivity extends Activity
{
Quiz quiz;
RadioButton rb1, rb2, rb3, rb4, rb5, rb6;
Button buttonOK;
String ans;
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
rb1=(RadioButton)findViewById(R.id.radio3);
rb2=(RadioButton)findViewById(R.id.radio4);
rb3=(RadioButton)findViewById(R.id.radio5);
rb4=(RadioButton)findViewById(R.id.radio6);
rb5=(RadioButton)findViewById(R.id.radio7);
rb6=(RadioButton)findViewById(R.id.radio8);
buttonOK=(Button)findViewById(R.id.button2);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup group2=(RadioGroup)findViewById(R.id.radioGroup3);
RadioButton answer2=(RadioButton)findViewById(group2.getCheckedRadioButtonId());
if (answer2.equals(rb4))
{
num = 5;
}
else if (answer2.equals(rb5))
{
num = 10;
}
else
{
num = 15;
}
RadioGroup group1=(RadioGroup)findViewById(R.id.radioGroup2);
RadioButton answer1=(RadioButton)findViewById(group1.getCheckedRadioButtonId());
if (answer1.equals(rb1))
{
ans = "easy";
}
else if (answer1.equals(rb2))
{
ans = "medium";
}
else
{
ans = "hard";
}
}
});
//*********Edit
//Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
//QuizActivity.this.startActivity(intent);
//finish();
Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
intent.putExtra("answer", ans);
intent.putExtra("question", num);
QuizActivity.this.startActivity(intent);
finish();
//*******Edit
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ui, menu);
return true;
}
}
Here Next Activity
package com.example.quizapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuestActivity extends Activity
{
Quiz quiz;
int score = 0;
int qid = 0;
Quiz.Question currentQuest;
TextView textQuestion;
RadioButton rba, rbb, rbc;
Button buttonNext;
QuizActivity qa = new QuizActivity();
String ans = qa.ans;
int num = qa.num;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//*********Edit
Intent intent= getActivity().getIntent();
String answer=intent.getStringExtra("answer");
int numOfQuestion=intent.getIntExtra("question", 0);
//quiz= new Quiz(ans, num);
quiz= new Quiz(answer,numOfQuestion);
//*******
currentQuest=quiz.getQuestionInstance(qid);
textQuestion=(TextView)findViewById(R.id.textView1);
rba=(RadioButton)findViewById(R.id.radio0);
rbb=(RadioButton)findViewById(R.id.radio1);
rbc=(RadioButton)findViewById(R.id.radio2);
buttonNext=(Button)findViewById(R.id.button1);
setQuestionView();
buttonNext.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
RadioGroup group=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(group.getCheckedRadioButtonId());
Log.d("yourans", currentQuest.getAnswer() + " " + answer.getText());
if(Integer.toString(currentQuest.getAnswer()).equals(answer.getText()) )
{
score++;
Log.d("score", "Your score" + score);
}
if(qid<num)
{
currentQuest=quiz.getQuestionInstance(qid);
setQuestionView();
}else
{
Intent intent = new Intent(QuestActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}
private void setQuestionView()
{
textQuestion.setText(currentQuest.getQuestion());
rba.setText(Integer.toString(currentQuest.getOptionA()));
rbb.setText(Integer.toString(currentQuest.getOptionB()));
rbc.setText(Integer.toString(currentQuest.getOptionC()));
qid++;
}
}

Categories