Android Studio Beginner: Keep Getting NoSuchMethodException for android.graphics.FontFamily. <init> [] - java

I keep getting this error whenever I run the application, which crashes every time I interact with it. The problem first occurred after I moved the original TextView around and altered the color and Font Style. I'm not sure why it's happening now, but it didn't happen before. I'm not exactly sure why this error is occurring either. Please help.
Below is the error message:
E/TypefaceCompatApi26Impl: Unable to collect necessary methods for class java.lang.NoSuchMethodException
java.lang.NoSuchMethodException: android.graphics.FontFamily.<init> []
This is the MainActivity class:
package com.example.exploreroptimizer;
import android.app.ActivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final Cleaner cleaner = new Cleaner();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cleanButton = findViewById(R.id.cleanButton);
final ProgressBar cleanBar = findViewById(R.id.progressBar);
final TextView progressUpdate = findViewById(R.id.progressUpdate);
System.out.println("success");
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Thread thread = new Thread() {
#Override
public void run() {
try {
final ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
final double a = mi.availMem / 0x100000L;
cleanBar.setProgress(20);
progressUpdate.setText("Cleaning Ram!");
Thread.sleep(1500);
cleanBar.setProgress(40);
progressUpdate.setText("Closing Unused Apps!");
Thread.sleep(1500);
cleanBar.setProgress(100);
progressUpdate.setText("Clearing Cache!");
Thread.sleep(1500);
Cleaner.deleteCache(getApplicationContext());
cleaner.killBackgroundProcesses(getApplicationContext(), getApplicationContext().getPackageManager());
cleaner.clearRAM();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "I have closed " + Cleaner.i + " apps, ", Toast.LENGTH_SHORT).show();
}
});
} catch (InterruptedException e) {
}
}
};
thread.start();
}
});
}
}
And this is the xml file code for the UI:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/cleanButton"
android:layout_width="172dp"
android:layout_height="166dp"
android:background="#drawable/cleanbutton"
android:fontFamily="sans-serif"
android:text="Clean"
android:textColor="#FFFFFF"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="312dp"
android:layout_height="382dp"
android:indeterminate="false"
android:max="0"
android:progress="0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/progressUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:text="TextView"
android:textColor="#0DB344"
android:textSize="18sp"
android:textStyle="normal|bold"
android:typeface="sans"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/progressBar" />
</androidx.constraintlayout.widget.ConstraintLayout>

Related

How to increase speed of BLE scanning Android Studio?

I want make some application, it will scanning nearby BLE and sending to server via MQTT. But the scanning proccess to slow. I want to increase the speed of scanning.
mainActivity.java
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
handler.postDelayed(this, 1000);
}
}, 1000);
final Handler handlerStop = new Handler();
handlerStop.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothAdapter.cancelDiscovery();
handlerStop.postDelayed(this, 2000);
}
}, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
bluetoothAdapter.startDiscovery();
}
}
}else {
bluetoothAdapter.cancelDiscovery();
}
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
mqttActivity.java
package com.example.mqtt_active;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MqttActivity extends AppCompatActivity {
private EditText server,port,id;
private Button save;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqtt);
server = findViewById(R.id.serverMQTT);
id = findViewById(R.id.mqttTopic);
port = findViewById(R.id.mqttPort);
save = findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity.mqtt_id = id.getText().toString();
MainActivity.mqtt_port = port.getText().toString();
MainActivity.mqtt_server = server.getText().toString();
startActivity(new Intent(MqttActivity.this,MainActivity.class));
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/turnon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.452" />
<Button
android:id="#+id/mqttSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set MQTT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.511"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/turnon"
app:layout_constraintVertical_bias="0.073" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.524"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mqttSet"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_mqtt.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/serverMQTT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Server"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:text="MQTT SERVER"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="MQTT TOPIC"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/serverMQTT" />
<EditText
android:id="#+id/mqttTopic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Topic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="MQTT PORT"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mqttTopic" />
<EditText
android:id="#+id/mqttPort"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Port"
app:layout_constraintBottom_toTopOf="#+id/saveButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/textView3"
app:layout_constraintVertical_bias="0.298" />
</androidx.constraintlayout.widget.ConstraintLayout>
How to increase speed of scanning nearby BLE? i expect from this forum, i can increase speed of scanning nearby BLE.

Android Studio - Database fetch to Textview not displaying correctly

I'm trying to display read from table in database, what i have written so far passes the json, however rather than showing in textview - it displays as a short popup, and then disappears.
Activity_tasks.java
package com.example.myapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class activity_tasks extends AppCompatActivity {
TextView TextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
Button button = findViewById(R.id.button1);
button.setOnClickListener(v -> showInfo());
TextView = findViewById(R.id.textView4);
downloadJSON();
}
private void downloadJSON() {
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
setTextView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://myurl.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
private void setTextView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] tasks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
tasks[i] = obj.getString("Task_title") + " " + obj.getString("task_description");
}
}
private void showInfo() {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
builder.setIcon(R.drawable.alert);
builder.setTitle(" ");
builder.setMessage("Lockdown sucks, we know.\nThat's why we created W2D.\n\nOver the comings weeks/months, we'll be adding some cool stuff here. So bear with...\n\nStay Home\nProtect the NHS\nSave Lives");
// Create and show the AlertDialog
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
I have a funny feeling this is something about me having a button requesting a pop-up too in the code, perhaps I haven't integrated the 2nd onCreate properly?
The above is linked to a textview on activity_tasks.xml
Example on phone:
activity.xml below:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
android:clickable="true"
tools:context=".MainActivity"
tools:ignore="ExtraText"
android:focusable="true">
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="95dp"
android:layout_height="90dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.946"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022"
app:srcCompat="#drawable/shortlogo"
tools:ignore="ContentDescription" />
<Button
android:id="#+id/button"
android:layout_width="158dp"
android:layout_height="153dp"
android:background="#drawable/circlebutton"
android:text="#string/hit_me_again"
android:textColor="#000"
android:textSize="8sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.896" />
<Button
android:id="#+id/button1"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/alert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.077"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06" />
<TextView
android:id="#+id/textView4"
android:layout_width="183dp"
android:layout_height="119dp"
android:textColor="#color/white"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/design"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.092"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/version_0_0_1"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.963"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
What you are seeing at the bottom is the toast you create in onPostExecute(). You receive the data, but then never update the text of the TextView. In setTextView() you could also do that:
textView.setText(json);
On another note: Don't use AsyncTasks anymore. They are deprecated and way too laborious. Also, to read the Json much more easily, you can use a library like Gson or Moshi.

How to stop fragments from being recreated in fragment transaction

I have an activity with multiple steps, each step being a fragment transaction with an edittext box, with a next/back button to navigate and initiate sending the users input data. I want to be able to move throughout the fragments with the text in each box staying static. I can move back no problem, but as soon as I click next the next fragment is recreated and everything is lost.
I tried:
using a dummy view in onCreateView
refetching the string in onCreate
setRetainInstance(true); in the constructor
Using a viewpager has other complications regarding receiving data which I was not able to solve despite many here attempting to help, so I have no choice but to use fragment transactions in my app.
main/FormActivity.java
package com.loopbreakr.formproject;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class FormActivity extends AppCompatActivity implements PageOne.ExitFormInteractionListener{
//DECLARE COMPONENTS
private FrameLayout fragmentContainer;
private Button backToMain;
private Button startForm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//FIND COMPONENTS IN XML
setContentView(R.layout.activity_form);
fragmentContainer = findViewById(R.id.frame_layout);
backToMain = findViewById(R.id.return_button);
startForm = findViewById(R.id.start_button);
//SET LISTENERS/INTENTS FOR BUTTONS
backToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
startForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragments();
}
});
}
private void openFragments() {
PageOne fragment1 = PageOne.newInstance();
FragmentManager fragmentManager =getSupportFragmentManager();
FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
beginTransaction.addToBackStack(null);
beginTransaction.add(R.id.frame_layout,fragment1,"PageOne_tag");
beginTransaction.commit();
}
#Override
public void onFragmentInteraction(String answerOneText) {
}
}
One of my fragments PageOne.java
package com.loopbreakr.formproject;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class PageOne extends Fragment {
View restored;
private static final String SAVED = "text";
private String savedText;
private String answerOneString;
private EditText answerOne;
private ExitFormInteractionListener mListener;
public PageOne() {
setRetainInstance(true);
}
public static PageOne newInstance() {
PageOne fragment = new PageOne();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
savedText = getArguments().getString(SAVED);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(restored == null){
restored = inflater.inflate(R.layout.fragment_page_one, container, false);
}
answerOne = restored.findViewById(R.id.answer_one);
Button exitForm = restored.findViewById(R.id.exit_form);
Button goNextTwo = restored.findViewById(R.id.gonext_two);
exitForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
returnToDesc();
}
});
goNextTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answerOneString = answerOne.getText().toString();
sendToTwo(answerOneString);
openSecondFragment();
}
});
return restored;
}
private void sendToTwo(String answerOneText) {
if(mListener != null){
mListener.onFragmentInteraction(answerOneText);
}
}
private void openSecondFragment() {
PageTwo fragment2 = PageTwo.newInstance(answerOneString);
FragmentTransaction fragTransition = getFragmentManager().beginTransaction();
fragTransition.replace(R.id.frame_layout, fragment2,"PageTwo_TAG");
fragTransition.addToBackStack(null);
fragTransition.commit();
}
private void returnToDesc(){
FragmentManager fragTransBack = getFragmentManager();
fragTransBack.popBackStack();
}
public interface ExitFormInteractionListener{
void onFragmentInteraction(String answerOneText);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
if (context instanceof ExitFormInteractionListener) {
mListener = (ExitFormInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
activity_form.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FormActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="32dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</LinearLayout>
<TextView
android:id="#+id/activity_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="#string/activity_title"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/return_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="8dp"
android:text="#string/return_text"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="#string/start_text"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintEnd_toEndOf="parent"
android:stateListAnimator="#null"/>
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
activity_page_one.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:clickable="true"
tools:context=".PageOne"
android:focusable="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:id="#+id/activity_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="#string/activity_title"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<Button
android:id="#+id/exit_form"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="8dp"
android:text="#string/back"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/gonext_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="#string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:stateListAnimator="#null"/>
<EditText
android:id="#+id/answer_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="start|top"
android:hint="#string/answer_one_hint"
android:inputType="textMultiLine|textAutoCorrect"
android:maxLines="4"
android:minLines="4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/activity_name"
android:stateListAnimator="#null"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
Thanks.

setContentView() not working as expected - why?

I am making an app an tried using setContentView in Android Studio when i used it the layout changed but the app is still using the first java it is not changing the code is given bellow
i tried changing the file up i also tried creating a new empty file but it didnt work
:-
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
private int progress = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressBar progressBar = findViewById(R.id.progressBar);
new Thread(new Runnable() {
#Override
public void run() {
while(progress < 100) {
progress++;
android.os.SystemClock.sleep(25);
mHandler.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(progress);
}
});
}
mHandler.post(new Runnable() {
#Override
public void run() {
setContentView(R.layout.activity_on_boarding);
}
});
}
}).start();
}
}
xml:-
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="187dp"
android:layout_height="141dp"
android:contentDescription="#string/logo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137"
app:srcCompat="#drawable/logo" />
<TextView
android:id="#+id/title"
android:layout_width="307dp"
android:layout_height="210dp"
android:text="#string/title"
android:textColor="#000000"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.52"
tools:fontFamily="casual"
/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="300dp"
android:layout_height="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.795" />
</androidx.constraintlayout.widget.ConstraintLayout>
second java:-
package com.thebetterside.wallex;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class OnBoarding extends AppCompatActivity {
private Button go = findViewById(R.id.go);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_boarding);
go.setOnClickListener(
new Button.OnClickListener(){
#Override
public void onClick(View v) {
setContentView(R.layout.activity_name);
}
}
);
}
}
2nd xml:-
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".OnBoarding">
<Button
android:id="#+id/go"
android:layout_width="351dp"
android:layout_height="44dp"
android:background="#drawable/rounded_corner_peach"
android:text="#string/go"
android:textColor="#000046"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.945" />
</androidx.constraintlayout.widget.ConstraintLayout>
You want to do startActivity(this, OnBoarding.class) instead of calling the setContentView()
setContentView() sets the layout for the current activity, it does not start the second one.
And judging from the code you posted, you want to transfer control to your other java file (OnBoarding.java) and that must be done by starting that activity explicitly.
EDIT: in your case, it'll most probably be MainActivity.this.startActivity(MainActivity.this, OnBoarding.class) because just this will point to the thread, instead of the enclosing Context/Activity

MediaRecorder setAudioSource failed -- App Crashes (possibly due to CM13)

I followed a video tutorial to write this code. I get a java.lang.RuntimeException: setAudioSource failed error that causes Unable to start activity
I am debugging on a 1st Gen Moto G with Cyanogenmod 13 installed.
My assumption is that my custom ROM has a conflict with MediaRecorder. Any ideas will be greatly appreciated!
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I should also mention that I have the correct permissions in AndroidManifest
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
MediaRecorder myAudioRecorder;
private String outputFile = null;
private Button start, stop, play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
play = (Button) findViewById(R.id.button3);
stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrec.3pg";
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
public void start(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch(IllegalStateException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
start.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(this, "Recording Started", Toast.LENGTH_SHORT).show();
}
public void stop(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(this, "Audio recorded successfully", Toast.LENGTH_SHORT).show();
}
public void play(View v) throws IOException {
MediaPlayer m = new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(this, "Playing Audio", Toast.LENGTH_SHORT).show();
}
UI / XML Editor
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.m4db0x.freestylerapdisorder.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:text="#string/recording_title"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:scaleType="fitXY"
android:src="#android:drawable/presence_audio_online"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView1"
android:layout_marginTop="67dp"
android:onClick="start"
android:text="#string/start" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/button1"
android:layout_below="#id/button1"
android:layout_alignRight="#id/textView1"
android:layout_marginTop="40dp"
android:onClick="stop"
android:text="#string/stop" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/button2"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:onClick="play"
android:text="#string/play" />
</RelativeLayout>
May be its too late but hope it would be helpful for someone...
Try to Change in your device
settings > privacy and safety > App Permission.
Try giving the required permission there too. Permission given in the device takes higher ranking than in the code.
That helped me out.

Categories