This question already has answers here:
java.lang.NoSuchMethodError: No static method getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;)
(16 answers)
Closed 5 years ago.
Getting a constant crash on the emulator when running a specific activity in my android project. The main activity of the project, as well as the splash screen run perfectly. The activity I am trying to run is quite complex, with information being read from a phpMyAdmin database.
I have read through the LogCat, but cannot seem to pinpoint the error that is causing the crash. Any nods in the right direction would be much appreciated. Don't have too much experience with this type of stuff.
Many thanks and apologies for the messy LogCat.
Maintenance Activity
package com.example.bs.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Maintenance extends AppCompatActivity {
private static final String PRODUCT_URL = "http://192.XXXXXXX/MyApi/api.php";
RecyclerView recyclerView;
ProductAdapter adapter;
List<Product> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintenance);
productList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
loadProducts ();
}
private void loadProducts () {
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products =new JSONArray(response);
for (int i = 0; i<products.length(); i++){
JSONObject productObject = products.getJSONObject(i);
int maintenance_id = productObject.getInt("maintenance_id");
String type = productObject.getString("type");
String property = productObject.getString("property");
String more_info = productObject.getString("more_info");
Double date = productObject.getDouble("date");
Product product = new Product(maintenance_id, type, property, more_info, date);
productList.add(product);
}
adapter = new ProductAdapter(Maintenance.this, productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Maintenance.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
}
activity_maintenance
<?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="com.example.benchalmers.myapplication.Maintenance">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
LogCat
02-06 12:11:42.195 4155-4155/? I/zygote: Not late-enabling -Xcheck:jni (already on)
02-06 12:11:42.409 4155-4155/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
02-06 12:11:43.494 4155-4155/com.example.bs.myapplication I/InstantRun: starting instant run server: is main process
02-06 12:11:43.665 4155-4155/com.example.bs.myapplication D/AndroidRuntime: Shutting down VM
02-06 12:11:43.671 4155-4155/com.example.bs.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bs.myapplication, PID: 4155
java.lang.NoSuchMethodError: No static method getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;)Landroid/graphics/Typeface; in class Landroid/support/v4/content/res/ResourcesCompat; or its super classes (declaration of 'android.support.v4.content.res.ResourcesCompat' appears in /data/app/com.example.bs.myapplication-EpCz2N67lH5I_Aiqfiskfg==/split_lib_dependencies_apk.apk)
at android.support.v7.widget.TintTypedArray.getFont(TintTypedArray.java:119)
at android.support.v7.widget.AppCompatTextHelper.updateTypefaceAndStyle(AppCompatTextHelper.java:208)
at android.support.v7.widget.AppCompatTextHelper.loadFromAttributes(AppCompatTextHelper.java:110)
at android.support.v7.widget.AppCompatTextHelperV17.loadFromAttributes(AppCompatTextHelperV17.java:38)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:81)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:71)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:67)
at android.support.v7.widget.Toolbar.setTitle(Toolbar.java:753)
at android.support.v7.widget.ToolbarWidgetWrapper.setTitleInt(ToolbarWidgetWrapper.java:261)
at android.support.v7.widget.ToolbarWidgetWrapper.setWindowTitle(ToolbarWidgetWrapper.java:243)
at android.support.v7.widget.ActionBarOverlayLayout.setWindowTitle(ActionBarOverlayLayout.java:621)
at android.support.v7.app.AppCompatDelegateImplV9.onTitleChanged(AppCompatDelegateImplV9.java:631)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.bs.myapplication.Maintenance.onCreate(Maintenance.java:34)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Adapter Class
package com.example.benchalmers.myapplication;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Context mCtx;
private List<Product> productList;
public ProductAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.list_layout, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Product product = productList.get(position);
holder.textViewType.setText(product.getType());
holder.textViewProperty.setText(product.getProperty());
holder.textViewMoreInfo.setText(String.valueOf(product.getMoreInfo()));
holder.textViewDate.setText(String.valueOf(product.getDate()));
//holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getImage()));
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textViewType, textViewProperty, textViewMoreInfo, textViewDate;
public ProductViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textViewType = itemView.findViewById(R.id.textViewType);
textViewProperty = itemView.findViewById(R.id.textViewProperty);
textViewMoreInfo = itemView.findViewById(R.id.textViewMoreInfo);
textViewDate = itemView.findViewById(R.id.textViewDate);
}
}
}
You should migrate to 26.0.0 or above version for your support v7 library.
This is issue in appcompat library and mentioned here
https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0
ResourcesCompat.getFont() throws exception
You should use the same version across all Android-related dependencies,its a best practice
You can check appcompat dependencies using
./gradlew :app:dependencyInsight --dependency com.android.support:appcompat --configuration debugCompileClasspath
It will give you info from where appcompat version is bumped to 27.0.2 from 26.1.0
Related
After successfully passing the login screen, I have called the AddJournalActivity.java class.. However, it crashes, as shown in the video.. What do I do? This is the code for AddJournalActivity.java
package com.project.journeyjournal;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.StorageReference;
public class AddJournalActivity extends AppCompatActivity implements View.OnClickListener {
private static final int GALLERY_CODE = 1;
private Button saveButton;
private ImageView addPhotoButton;
private EditText titleEditText;
private EditText thoughtsEditText;
private ImageView imageView;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
//connection to firestore
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private StorageReference storageReference;
private CollectionReference collectionReference = db.collection("Journal");
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_journal);
firebaseAuth = FirebaseAuth.getInstance();
titleEditText = findViewById(R.id.post_title_et);
thoughtsEditText = findViewById(R.id.post_description_et);
imageView = findViewById(R.id.post_imageView);
saveButton = findViewById(R.id.post_save_journal_button);
saveButton.setOnClickListener(this);
addPhotoButton = findViewById(R.id.postCameraButton);
addPhotoButton.setOnClickListener(this);
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null){
} else{
}
}
};
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.post_save_journal_button:
//save Journal
break;
case R.id.postCameraButton:
//get image from camera or gallery
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_CODE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK ){
if (data != null){
imageUri = data.getData();
imageView.setImageURI(imageUri);//show image
}
}
}
#Override
protected void onStart() {
super.onStart();
user = firebaseAuth.getCurrentUser();
firebaseAuth.addAuthStateListener((authStateListener));
}
#Override
protected void onStop() {
super.onStop();
if (firebaseAuth!= null){
firebaseAuth.removeAuthStateListener(authStateListener);
}
}
}
I tried opening other pages instead of AddJournalActivity after the login activity, and it was working fine. If I delete all the code in the .java file, then the layout file opens just fine. So I assume that the problem is with AddJournalActivity.java. But I am unable to find it.
I have added the Logcat if it helps.2022-04-06 11:19:46.326 15573-15573/com.project.journeyjournal E/AndroidRuntime: FATAL EXCEPTION: main Process: com.project.journeyjournal, PID: 15573 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.journeyjournal/com.project.journeyjournal.AddJournalActivity}: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 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:2044) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:224) at android.app.ActivityThread.main(ActivityThread.java:7560) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) Caused by: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView at com.project.journeyjournal.AddJournalActivity.onCreate(AddJournalActivity.java:51) at android.app.Activity.performCreate(Activity.java:7893) at android.app.Activity.performCreate(Activity.java:7880) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 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:2044) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:224) at android.app.ActivityThread.main(ActivityThread.java:7560) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
I watched your video. Your app crashes after logging in.
By observing your logcat, I can see an error causing with CardView and ImageView. You didn't provide your XML Code, so I'm not sure what exactly is the cause.
Here check this line-
ComponentInfo{com.project.journeyjournal/com.project.journeyjournal.AddJournalActivity}:
java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView
Solution
Possibly you have a CardView in XML which has an ID post_imageView or postCameraButton and you're binding this ID to ImageView by calling
imageView = findViewById(R.id.post_imageView);
or
addPhotoButton = findViewById(R.id.postCameraButton);
Check your IDs in XML and let me know the update.
Im new to android and they(some people :) ) gave me an half developed app and im still confused about some things.
Im getting an error which i can't understand what it means. So the error is what i wrote in the title : java.lang.IllegalStateException: FragmentManager has not been attached to a host, and is hapening when this activity runs:
package com.example.loginregistodb;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
public class ClienteActivity extends AppCompatActivity {
Spinner tipo_intervencao;
Button bt_cliente_seguinte;
EditText et_inserir_cliente;
ImageView icon1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente);
bt_cliente_seguinte = (Button) findViewById(R.id.bt_cliente_seguinte);
et_inserir_cliente = findViewById(R.id.et_inserir_cliente);
tipo_intervencao = findViewById(R.id.tipo_intervencao);
icon1 = findViewById(R.id.icon2);
bt_cliente_seguinte.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cliente = et_inserir_cliente.getText().toString();
String tipoIntervencao = "" + tipo_intervencao.getSelectedItem().toString();
preencherExcel Excel = new preencherExcel();
Excel.entradaWhatsapp(cliente, tipoIntervencao);
if (cliente.equalsIgnoreCase("")) {
Toast.makeText(ClienteActivity.this, "Preencha o campo Cliente!", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(ClienteActivity.this, EmpresaActivity.class);
startActivity(i);
}
}
});
}
}
EDIT :
the error message i get is this :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginregistodb, PID: 15275
java.lang.IllegalStateException: FragmentManager has not been attached to a host.
at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1938)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1996)
at androidx.fragment.app.FragmentManager.executePendingTransactions(FragmentManager.java:600)
at com.google.firebase.firestore.core.ActivityScope.lambda$onFragmentActivityStopCallOnce$1(ActivityScope.java:180)
at com.google.firebase.firestore.core.ActivityScope$$ExternalSyntheticLambda1.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
I was making a code to create a show list by ListView{in content_main.xml} like contact view.
I build a database in the (SQLite Expert Professional) with a table(name: "contact") that was contained a few name and family and numbers, with ID,NAME,fAMILY and PHONE NUMBER columns.
ID was unique, auto increment and primary key...other were Text except number that was CHAR.
then I calling them to my ListView as you see in below.(before it I made a row_list activity to made my listview , custom) but there was an Error and I can't find it.
{I could find my database.db file with that's table in the source data files that means my mistake wasn't from creating database.}
plz help me.I wanna learn android (as fast as i can) to get a JOB and I need it..
Errors.Android Monitor.Logcat
09-08 05:27:32.005 5692-5692/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x94c4fb20)
09-08 05:27:32.005 5692-5692/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: mizco.phonebook, PID: 5692
java.lang.RuntimeException: Unable to start activity ComponentInfo{mizco.phonebook/mizco.phonebook.Main}: android.database
.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at mizco.phonebook.database.getfulllist(database.java:97)
at mizco.phonebook.Main.onCreate(Main.java:36)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Main.java
package mizco.phonebook;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends AppCompatActivity {
private database db;
private String [][] res ;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
list = (ListView) findViewById(R.id.main_list);
db = new database(this);
db.startusing();
db.open();
res = db.getfulllist();
db.close();
list.setAdapter(new AA());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
class AA extends ArrayAdapter<String>{
public AA() {
super(Main.this, R.layout.row_list, res[0]);
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater in = getLayoutInflater();
View row = in.inflate(R.layout.row_list,parent,false);
TextView name = (TextView) row.findViewById(R.id.row_name);
TextView number = (TextView) row.findViewById(R.id.row_number);
name.setText(res[0][position]+" "+res[1][position]);
number.setText(res[2][position]);
return row;
}
}
}
Class : database.java
package mizco.phonebook;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Mahdi on 9/2/2017.
*/
public class database extends SQLiteOpenHelper {
public static String dbname= "database";
public static String dbpath="";
private Context mctxt;
private SQLiteDatabase mydb;
public database(Context context) {
super(context, dbname, null, 1);
mctxt = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private boolean existdatabase(){
File m312 = new File(dbpath+dbname);
return m312.exists();
}
private void copydatabase(){
try {
InputStream IS = mctxt.getAssets().open(dbname);
OutputStream OS = new FileOutputStream(dbpath+dbname);
byte[] buffer = new byte[1024];
int length;
while ((length = IS.read(buffer))>0){
OS.write(buffer,0,length);
}
OS.flush();
OS.close();
IS.close();
} catch (Exception e) {
}
}
public void open(){
mydb = SQLiteDatabase.openDatabase(dbpath+dbname, null, SQLiteDatabase.OPEN_READWRITE);
}
public void close(){
mydb.close();
}
public void startusing () {
dbpath = mctxt.getFilesDir().getParent() + "/databases/";
if (!existdatabase()) {
this.getWritableDatabase();
copydatabase();
}
}
public String[][] getfulllist(){
Cursor cu = mydb.rawQuery("select * from Contact",null);
String [][] r = new String[3][cu.getCount()];
for (int i= 0;i<=cu.getCount();i++){
cu.moveToPosition(i);
r[0][i]=cu.getString(1);
r[1][i]=cu.getString(2);
r[2][i]=cu.getString(3);
}
return r;
}
}
You're stepping off the end of the cursor. Your code should read
for (int i= 0;i < cu.getCount();i++){
cu.moveToPosition(i);
r[0][i]=cu.getString(1);
r[1][i]=cu.getString(2);
r[2][i]=cu.getString(3);
}
return r;
Summary: MainActivityFragment passes passes an intent to DetailedActivity when an item is clicked to display detailed data. Since I want to display these within a Two-Pane interface, I needed to make the DetailedActivity a fragment.
Problem : Whenever clicking on the item in MainActivityFragment to launch the intent for DetailedActivityFragment, I get an error saying its unable to start or inflate the activity. The detailedActivity for sake here is named "test" and "testFragment". It appears as though it points to line 25 of the activity_test.xml which is the line of include layout="#...".
I have left the fragment_test.xml out due to its length but i will provide a github link to anyone whom may want to see it or the manifest.
Im currently a novice to the android world so any help is appriciated =)! This branch of my project is a huge mess right now experimenting with things right now so pardon the mess...
Github Link:https://github.com/Rykuno/Flix-Viewer/tree/tablet/app/src/main/java/com/rykuno/movietestapp/Activities
FATAL EXCEPTION: main
Process: com.rykuno.movietestapp, PID: 14281
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rykuno.movietestapp/com.rykuno.movietestapp.Activities.test}: android.view.InflateException: Binary XML file line #25: Binary XML file line #1: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #25: Binary XML file line #1: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
at android.app.Activity.setContentView(Activity.java:2172)
at com.rykuno.movietestapp.Activities.test.onCreate(test.java:14)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:941)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
at android.app.Activity.setContentView(Activity.java:2172)
at com.rykuno.movietestapp.Activities.test.onCreate(test.java:14)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: Target must not be null.
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:618)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)
at com.rykuno.movietestapp.Activities.testFragment.setViewData(testFragment.java:100)
at com.rykuno.movietestapp.Activities.testFragment.onCreateView(testFragment.java:87)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2288)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:754)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:941)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
at android.app.Activity.setContentView(Activity.java:2172)
at com.rykuno.movietestapp.Activities.test.onCreate(test.java:14)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here is the code to the Activity Files vvv
package com.rykuno.movietestapp.Activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.rykuno.movietestapp.R;
public class test extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
And the fragment
package com.rykuno.movietestapp.Activities;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.rykuno.movietestapp.Adapter.TrailerAdapter;
import com.rykuno.movietestapp.BuildConfig;
import com.rykuno.movietestapp.Data.DatabaseHelper;
import com.rykuno.movietestapp.R;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* A placeholder fragment containing a simple view.
*/
public class testFragment extends Fragment {
private static final String MOVIEKEYS = "videoKeys";
private String movieVideoUrl;
private List<String> movieKeys = new ArrayList<>();
private String mPoster;
private String mOriginalTitle;
private String mPlot;
private String mReleaseDate;
private String mBackDrop;
private String mRating;
private boolean mFavorited = false;
private int mId;
private DatabaseHelper db;
private TrailerAdapter mTrailerAdapter;
#Bind(R.id.title_textView)
TextView mTitleTextView;
#Bind(R.id.rating_textView)
TextView mRatingTextView;
#Bind(R.id.plot_textView)
TextView mPlotTextView;
#Bind(R.id.backdrop_image)
ImageView mBackdropImageView;
#Bind(R.id.poster_imageView)
ImageView mPosterImageView;
#Bind(R.id.released_textView)
TextView mReleaseDateTextView;
#Bind(R.id.comments_button)
Button mCommentsButton;
#Bind(R.id.favorite_imageView)
ImageView mFavoritesImageView;
#Bind(R.id.trailer_gridview)
GridView mGridView;
public testFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_test, container, false);
db = new DatabaseHelper(getActivity());
ButterKnife.bind(getActivity());
extractExtras();
setViewData();
getMovieYoutubeHandle();
setClickItems();
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void setViewData() {
Picasso.with(getActivity()).load("http://image.tmdb.org/t/p/w780/" + mBackDrop).into(mBackdropImageView);
Picasso.with(getActivity()).load("http://image.tmdb.org/t/p/w342/" + mPoster).into(mPosterImageView);
mTitleTextView.setText(mOriginalTitle);
mRatingTextView.setText(mRating + "/10");
mPlotTextView.setText(mPlot);
mReleaseDateTextView.setText(mReleaseDate);
}
private void extractExtras() {
mPoster = getActivity().getIntent().getStringExtra("poster");
mOriginalTitle = getActivity().getIntent().getStringExtra("title");
mPlot = getActivity().getIntent().getStringExtra("plot");
mReleaseDate = getActivity().getIntent().getStringExtra("releaseDate");
mBackDrop = getActivity().getIntent().getStringExtra("backdrop");
mRating = getActivity().getIntent().getStringExtra("rating");
mId = getActivity().getIntent().getIntExtra("id", 0);
mFavorited = getActivity().getIntent().getBooleanExtra("favorited", false);
}
private void getMovieYoutubeHandle(){
movieVideoUrl = "http://api.themoviedb.org/3/movie/"+mId+"/videos?api_key="+ BuildConfig.MY_MOVIE_DB_API_KEY;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(movieVideoUrl).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String jsonData = response.body().string();
try {
movieKeys = Arrays.asList(getTrailerData(jsonData));
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mTrailerAdapter.setListData(movieKeys);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private String[] getTrailerData(String jsonData) throws JSONException {
JSONObject trailerDetails = new JSONObject(jsonData);
JSONArray results = trailerDetails.getJSONArray("results");
String[] keyArray = new String[results.length()];
for(int i = 0; i<results.length(); i++){
JSONObject keyResults = results.getJSONObject(i);
String youtubeKey = keyResults.getString("key");
keyArray[i] = youtubeKey;
}
return keyArray;
}
private void setClickItems() {
//initializes gridview for trailers and onItemClicks
mTrailerAdapter = new TrailerAdapter(getActivity(), R.layout.trailer_item, movieKeys);
mGridView.setAdapter(mTrailerAdapter);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String keyPosition = movieKeys.get(position).toString();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=" + keyPosition)));
}
});
//onClick launches the CommentsActivity
mCommentsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), CommentsActivity.class);
intent.putExtra("id", mId);
startActivity(intent);
}
});
//onClick for favorites
mFavoritesImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db = new DatabaseHelper(getActivity());
boolean isInserted = db.insertData(getActivity(), mId, mOriginalTitle, mPlot, mBackDrop, mPoster, mRating, mReleaseDate);
if (isInserted = true) {
mFavoritesImageView.setImageResource(android.R.drawable.star_big_on);
Log.v(DetailedMovie.class.getSimpleName(), "entry worked");
} else if (isInserted = false) {
Log.v(DetailedMovie.class.getSimpleName(), "entry failed");
}
}
});
}
#Override
public void onSaveInstanceState(Bundle outState) {
ArrayList<String> toSave = movieKeys instanceof ArrayList ?
(ArrayList<String>) movieKeys : new ArrayList<>(movieKeys);
outState.putStringArrayList(MOVIEKEYS, toSave);
super.onSaveInstanceState(outState);
}
}
As well as the layout files.
activity_test.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true"
tools:context="com.rykuno.movietestapp.Activities.test">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_test"/>
</android.support.design.widget.CoordinatorLayout>
content_test.xml
<fragment android:id="#+id/fragment1"
android:name="com.rykuno.movietestapp.Activities.testFragment"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_test"/>
make sure to use:
import android.support.v4.app.Fragment;
And also make sure that the Activity that is using the fragment(s) extends FragmentActivity instead of the regular Activity,
import android.support.v4.app.FragmentActivity;
to get the FragmentActivity class.
One think I found is add app:layout_behaviour to include tag and not inside content_test.xml
<include layout="#layout/content_test"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
And your project got many NPE unable to test more.
I'm working on an application which will have a ListView alongwith a Button to add items to the ListView dynamically. I've made a custom adapter for the ListView. My idea is when the user will tap the Button it'll show an AlertDialog with a TextView and two buttons, "OK" and "Cancel". This my activity where the ListView will be shown -
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Add_Topics extends Activity {
AddTopics_MenuAdapter adapter;
ListView topics_list;
public ArrayList<topic> the_subjects;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__topics);
the_subjects = Model.loadTopics();
topics_list = (ListView) findViewById(R.id.topics_list);
overridePendingTransition(R.anim.reverse_in_left, R.anim.reverse_out_left);
Animation enter = AnimationUtils.loadAnimation(getBaseContext(), R.anim.upcoming_menu);
Animation enter_slow = AnimationUtils.loadAnimation(getBaseContext(), R.anim.enter_l2r_slide);
TextView des = (TextView)findViewById(R.id.des_at);
TextView title = (TextView)findViewById(R.id.title_at);
Button add_topic = (Button)findViewById(R.id.add_topic_button);
Typeface roboto_lt = Typeface.createFromAsset(getAssets(), "Roboto-Light.ttf");
des.setTypeface(roboto_lt);
title.setTypeface(roboto_lt);
add_topic.setTypeface(roboto_lt);
title.startAnimation(enter);
des.startAnimation(enter_slow);
adapter = new AddTopics_MenuAdapter(this, the_subjects);
topics_list.setAdapter(adapter);
}
public void onClickAddTopic(View v) {
showDialog(0);
}
protected Dialog onCreateDialog(int id) {
switch(id) {
case 0:
LayoutInflater li = LayoutInflater.from(this);
View edt_txt_add_tpc = li.inflate(R.layout.add_topics_res, null);
edt_txt_add_tpc.requestFocus();
final EditText tpc_nm = (EditText) edt_txt_add_tpc.findViewById(R.id.topic_name);
Builder bld = new AlertDialog.Builder(this);
bld.setIcon(R.drawable.ic_launcher);
bld.setTitle("Add Topic/Subject");
bld.setView(edt_txt_add_tpc);
bld.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButon) {
String new_topic_name = tpc_nm.getText().toString();
adapter = null;
the_subjects.add(new topic(new_topic_name));
adapter = new AddTopics_MenuAdapter(getBaseContext(), the_subjects);
adapter.notifyDataSetChanged();
}
});
bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
return bld.create();
}
return null;
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_add__topics, menu);
return true;
}
}
But, the whole application crashes when I tap the "OK" button. It works fine if I omit the_subjects.add(new topic(new_topic_name));. But then the newly added item disappears when I reload the activity.
Here is my custom ListView adapter -
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class AddTopics_MenuAdapter extends ArrayAdapter<topic> {
private final Context context;
final ArrayList<topic> topics;
public AddTopics_MenuAdapter(Context context, ArrayList<topic> topics) {
super(context, R.layout.add_topics_menu, topics);
this.context = context;
this.topics = topics;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View topicsView = inflater.inflate(R.layout.add_topics_menu, parent, false);
TextView topic_name = (TextView) topicsView.findViewById(R.id.topic_title);
Typeface rbt_lt = Typeface.createFromAsset(getContext().getAssets(), "Roboto-Light.ttf");
Animation enter = AnimationUtils.loadAnimation(getContext(), R.anim.upcoming_menu);
topic_name.setText(topics.get(position).toString());
topic_name.setTypeface(rbt_lt);
topic_name.setAnimation(enter);
return topicsView;
}
}
Model.java -
import java.util.ArrayList;
import android.util.Log;
import android.widget.Toast;
public class Model {
public static ArrayList<topic> list_of_topics;
public static String[] subjects;
public static ArrayList<topic> loadTopics() {
list_of_topics = new ArrayList<topic>();
list_of_topics.add(new topic("History"));
list_of_topics.add(new topic("Geography"));
return list_of_topics;
}
}
topic.java -
public class topic {
String Topic;
public topic(String topic) {
Topic = topic;
}
}
Here's the log of my error -
03-07 18:13:28.271: E/AndroidRuntime(20349): FATAL EXCEPTION: main
03-07 18:13:28.271: E/AndroidRuntime(20349): java.lang.NullPointerException
03-07 18:13:28.271: E/AndroidRuntime(20349): at com.Swap.StudyBuddy.Add_Topics$1.onClick(Add_Topics.java:80)
03-07 18:13:28.271: E/AndroidRuntime(20349): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:170)
03-07 18:13:28.271: E/AndroidRuntime(20349): at android.os.Handler.dispatchMessage(Handler.java:107)
03-07 18:13:28.271: E/AndroidRuntime(20349): at android.os.Looper.loop(Looper.java:194)
03-07 18:13:28.271: E/AndroidRuntime(20349): at android.app.ActivityThread.main(ActivityThread.java:5409)
03-07 18:13:28.271: E/AndroidRuntime(20349): at java.lang.reflect.Method.invokeNative(Native Method)
03-07 18:13:28.271: E/AndroidRuntime(20349): at java.lang.reflect.Method.invoke(Method.java:525)
03-07 18:13:28.271: E/AndroidRuntime(20349): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-07 18:13:28.271: E/AndroidRuntime(20349): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
03-07 18:13:28.271: E/AndroidRuntime(20349): at dalvik.system.NativeStart.main(Native Method)
I can't figure out figure out how to modify the ArrayList<topic> without crashing the app. Please help me to solve this problem. Thanks in advance!!
You will replace your code...Your Code is
String new_topic_name = tpc_nm.getText().toString();
adapter = null;
the_subjects.add(new topic(new_topic_name));
adapter = new AddTopics_MenuAdapter(getBaseContext(), the_subjects);
adapter.notifyDataSetChanged();
You don't want to set null for your adapter So you will use
adapter.clear();
It will delete your whole data in your adapter Just replace with that single line