This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am new to Java and Android When Ever I tried to connect my android app to SQLite it generates a null point error, every time it crashes app on calling the onCreate method on Database helper class.
I am unable to find the error in my code so please someone help me.
MainActivity.java Code:
package com.example.sdreddy.dbfinal;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
DbNeed dbn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button dd=(Button)findViewById(R.id.button);
dd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView tv = (TextView) findViewById(R.id.textView);
try {
dbn.Addd("SDREDDY");
String zz = dbn.getdata();
tv.setText(zz);
}
catch (Exception ee){
tv.setText((CharSequence) ee.toString());
}
}
});
}
}
DbNeed.java Code
package com.example.sdreddy.dbfinal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
/**
* Created by SDREDDY on 26-04-2018.
*/
public class DbNeed extends SQLiteOpenHelper {
public static final String dbname="Database.db";
public static final String tblname="MyTable";
public DbNeed(Context context) {
super(context, dbname, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table if not exists "+tblname+" (id text,value text)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop table if exists "+tblname);
onCreate(sqLiteDatabase);
}
public void Addd(String Name){
SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
ContentValues cv=new ContentValues();
Random r=new Random();
String idz=String.valueOf(r.nextInt());
cv.put("id",idz);
cv.put("name",Name);
sqLiteDatabase.insert(tblname,null,cv);
sqLiteDatabase.close();
}
public String getdata(){
SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
String qu="SELECT * FROM "+tblname;
Cursor crz=sqLiteDatabase.rawQuery(qu,null);
sqLiteDatabase.close();
String sim=crz.getString(0);
return sim;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sdreddy.dbfinal.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="30sp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Log cat of my Code
After the line setContentView(R.layout.activity_main); add the following :-
dbn = new DbNeed(this);
This will instantiate (set) dbn which has at this stage only been declared and is therefore null.
Related
error : "Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference"
so what should ı do to fix it if someone help me ı'll be so gratefull
here is my codes
cardbg.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#color/purple_500"
android:id="#+id/cardbg">
</LinearLayout>
activit_ymain.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayoutxmlns: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">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints">
<LinearLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:orientation="vertical" />
</androidx.core.widget.NestedScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.thehuman.todo;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
LinearLayout main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main = findViewById(R.id.main);
card first = new card(MainActivity.this);
main.addView(first);
}
}
class card extends LinearLayout{
card self;
LinearLayout bg,main;
Button clon,delete;
#SuppressLint("ResourceAsColor")
public card(Context context) {
super(context);
self=this;
main = findViewById(R.id.main);
bg = findViewById(R.id.cardbg);
clon = new Button(context);
clon.setBackgroundColor(R.color.white);
clon.setPadding(20,20,20,20);
clon.setTextColor(R.color.teal_200);
clon.setText("clon me");
delete = new Button(context);
delete.setBackgroundColor(R.color.black);
delete.setTextColor(R.color.teal_200);
delete.setPadding(20,20,20,20);
delete.setText("delete me");
bg.addView(clon);
bg.addView(delete);
clon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
card cloncard = new card(context);
main.addView(cloncard);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
main.removeView(self);
}
});
}
}
I suppose you are getting null object reference error in class Card. Because you are using bg = findViewById(R.id.cardbg);. You can not find cardbg.xml using findViewById because cardbg.xml have not been attached to you activity layout. You have to inflate your xml by yourself using an inflater.
Use
bg = LayoutInflater.from(context).inflate(R.layout.cardbg, null).findViewById(R.id.cardbg);
This question already has answers here:
RecyclerView adapter show only first item
(3 answers)
Closed 3 years ago.
I use recycler view before and i never have this problems. The principal difference between the other recycler views that i made is that i use SQLite for this one.
I want all the items appears one between other and without white spaces between them.
LEADER BOARD ACTIVITY WHERE I INITIALIZE MY RECYCLER
public class LeaderBoard extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerController mAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leader_board);
DaoSQLite manager=new DaoSQLite(this);
SQLiteDatabase db=manager.getReadableDatabase();
layoutManager=new LinearLayoutManager(this);
recyclerView=findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
mAdapter=new RecyclerController(manager.getSortScores());
recyclerView.setAdapter(mAdapter);
}
}
VIEW FOR RECYCLER
<?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"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/lbName"
android:layout_width="129dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Name"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lbLevel2"
android:layout_width="109dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="154dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Level"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lbScore"
android:layout_width="132dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="266dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Score"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<View
android:id="#+id/view"
android:layout_width="wrap_content"
android:layout_height="79dp"
android:background="#604697"
android:backgroundTint="#34BE3838"
android:backgroundTintMode="src_in"
android:hapticFeedbackEnabled="false" />
</RelativeLayout>
THIS IS THE SQLite DAO
package com.example.quizappjava.DataBase;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.quizappjava.Beans.User;
public class DaoSQLite extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Game.db";
private static final String TABLE_NAME_SCORES = "puntuaciones";
private SQLiteDatabase sqLiteDatabase = getWritableDatabase();
public DaoSQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+ TABLE_NAME_SCORES +" (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT (15) NOT NULL,score INTEGER NOT NULL, level INTEGER NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getSortScores(){
return getReadableDatabase().query(TABLE_NAME_SCORES,null,null,null,null,null,"score");
}
public void insertNewScore(User user){
sqLiteDatabase.insert(TABLE_NAME_SCORES,null,user.toContentValues());
}
}
RECYCLER CONTROLLER
package com.example.quizappjava.JavaClasses;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.quizappjava.Beans.User;
import com.example.quizappjava.R;
import java.util.ArrayList;
public class RecyclerController extends RecyclerView.Adapter<RecyclerController.ViewHolder> {
private ArrayList<User> userArraList = new ArrayList<User>();
public RecyclerController(Cursor queryRequest) {
ParseData(queryRequest);
}
private void ParseData(Cursor queryRequest) {
for (queryRequest.moveToFirst(); !queryRequest.isAfterLast(); queryRequest.moveToNext()) {
userArraList.add(
new User(
queryRequest.getString(queryRequest.getColumnIndex("name")),
queryRequest.getInt(queryRequest.getColumnIndex("score")),
queryRequest.getInt(queryRequest.getColumnIndex("level"))
));
}
}
#NonNull
#Override
public RecyclerController.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerController.ViewHolder holder, int position) {
holder.user=userArraList.get(position);
holder.lbName.setText(userArraList.get(position).getName());
holder.lbScore.setText(userArraList.get(position).getScore()+"");
holder.lbLevel.setText(userArraList.get(position).getLevel()+"");
}
#Override
public int getItemCount() {
return userArraList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView lbName;
private TextView lbScore;
private TextView lbLevel;
private User user;
public ViewHolder(#NonNull View itemView) {
super(itemView);
lbName=itemView.findViewById(R.id.lbName);
lbLevel=itemView.findViewById(R.id.lbLevel2);
lbScore=itemView.findViewById(R.id.lbScore);
}
}
}
This images shows how i see the leader board when i execute the app, the first image is how i see one item and the second one is the blank space between both items
Try
edit this :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="match_parent">
To:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="wrap_content">
You should have the same problem explained and resolved here.
The Relative Layout passed to your Recycler has android:layout_height="match_parent, but should have android:layout_height="wrap_content, otherwhise every item will be height as much as RecylerView is.
You have to adjust your recyclerview's cell height to wrap content instead of match parent:
VIEW FOR RECYCLER
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="wrap_content">
match_parent height would scale the cell to the height of the parent view
i am making an application where data is being saved in the database.i am lacking in displaying the data in the recyclerview using recyclerview adapter.don't know what code should be written. please check.
here is my files: MainActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView applist;
ArrayList<Guides> guides;
GuideAdapter adapter;
GuideDB guideDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideDB = new GuideDB(this);
guides = new ArrayList<>();
applist = (RecyclerView) findViewById(R.id.app_list);
applist.setHasFixedSize(true);
applist.setLayoutManager(new LinearLayoutManager(this));
adapter = new GuideAdapter(this,guides);
applist.setAdapter(adapter);
try {
Cursor cursor = guideDB.getGuides("SELECT * FROM GUIDE_LIST");
while (cursor.moveToNext()){
int guide_id = cursor.getInt(0);
String post_tile = cursor.getString(1);
String post_desc = cursor.getString(2);
String post_address = cursor.getString(3);
byte [] post_image = cursor.getBlob(4);
Guides g = new Guides(guide_id,post_tile,post_desc,post_address,post_image);
guides.add(g);}
}catch (Exception e){e.printStackTrace();}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this,PostActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
PostActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class PostActivity extends AppCompatActivity {
public ImageButton mSelectImage;
public EditText mPostTitle;
public EditText mPostDesc;
public EditText mPostAddress;
public Button mSubmitbtn;
private static final int GALLERY_REQUEST= 1;
GuideDB guideDB;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
guideDB = new GuideDB(this);
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mPostAddress = (EditText) findViewById(R.id.addressField);
mSubmitbtn = (Button) findViewById(R.id.submitButton);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GALLERY_REQUEST);
}
});
mSubmitbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(!mPostTitle.getText().toString().isEmpty() && !mPostDesc.getText().toString().isEmpty() && !mPostAddress.getText().toString().isEmpty())
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,50,outputStream);
byte[] byteArray = outputStream.toByteArray();
try {
guideDB.addGuide(mPostTitle.getText().toString(),
mPostDesc.getText().toString(),
mPostAddress.getText().toString(),byteArray
);
Toast.makeText(getApplicationContext(),"Added successfully!",Toast.LENGTH_LONG).show();
}catch (Exception e){e.printStackTrace();}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri mimageUri = data.getData();
try {
InputStream inputstream = getContentResolver().openInputStream(mimageUri);
bitmap = BitmapFactory.decodeStream(inputstream);
mSelectImage.setImageBitmap(bitmap);
}catch (FileNotFoundException e){e.printStackTrace();}
}
}
}
GuideDB.java
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
/**
* Created by 291 on 14.12.2017.
*/
public class GuideDB extends SQLiteOpenHelper {
private static final int DATABASE_VERSION= 1;
private static final String DATABASE_NAME= "guide_db";
private static final String TABLE_NAME = "GUIDE_LIST";
private static String GUIDE_ID = "guide_id";
private static String GUIDE_TITLE = "guide_title";
private static String GUIDE_DESC = "guide_desc";
private static String GUIDE_ADDRESS = "guide_address";
private static String GUIDE_IMG = "guides_image";
public GuideDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE" + TABLE_NAME + "("
+ GUIDE_ID + "INTEGER PRIMARY KEY AUTOINCREMENT"
+ GUIDE_TITLE + "TEXT"
+ GUIDE_DESC + "TEXT"
+ GUIDE_ADDRESS + "TEXT"
+ GUIDE_IMG + "BLOB" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public void addGuide (String title,String desc,String address,byte[] image){
SQLiteDatabase gdb = getWritableDatabase();
try
{
String sql = "INSERT INTO GUIDE_LIST VALUES(NULL,?,?,?)";
SQLiteStatement statement = gdb.compileStatement(sql);
statement.clearBindings();
statement.bindString(1,title);
statement.bindString(2,desc);
statement.bindString(3,address);
statement.bindBlob(4,image);
statement.execute();
}catch (Exception e){e.printStackTrace();}
}
public Cursor getGuides(String sql){
SQLiteDatabase gdb = getReadableDatabase();
return gdb.rawQuery(sql,null);
}
}
GuideAdapter.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.ArrayList;
/**
* Created by 291 on 14.12.2017.
*/
public class GuideAdapter extends RecyclerView.Adapter<GuideAdapter.ViewHolder> {
private Context ctx;
private ArrayList<Guides> guidelist;
public GuideAdapter(Context ctx, ArrayList<Guides> guidelist) {
this.ctx = ctx;
this.guidelist = guidelist;
}
#Override
public GuideAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.guide_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(GuideAdapter.ViewHolder holder, int position) {
Guides guides = guidelist.get(position);
holder.psttitle.setText(guides.getPost_title());
holder.pstdesc.setText(guides.getPost_desc());
holder.pstaddres.setText(guides.getPost_address());
byte [] postimg = guides.getPost_image();
Bitmap bitmap = BitmapFactory.decodeByteArray(postimg,0,postimg.length);
holder.pstimg.setImageBitmap(bitmap);
}
#Override
public int getItemCount() {
return guidelist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public ImageView pstimg;
public TextView psttitle;
public TextView pstdesc;
public TextView pstaddres;
public int id;
public ViewHolder(View itemView) {
super(itemView);
pstimg = (ImageView) itemView.findViewById(R.id.post_image);
psttitle = (TextView) itemView.findViewById(R.id.post_title);
pstdesc = (TextView) itemView.findViewById(R.id.post_title);
pstaddres = (TextView) itemView.findViewById(R.id.post_address);
}
}
}
Guides.java
public class Guides {
private int guide_id;
private String post_title,post_desc,post_address;
private byte [] post_image;
public Guides(int guide_id, String post_title, String post_desc, String post_address, byte [] post_image) {
this.guide_id = guide_id;
this.post_title = post_title;
this.post_desc = post_desc;
this.post_address = post_address;
this.post_image = post_image;
}
public int getGuide_id() {
return guide_id;
}
public void setGuide_id(int guide_id) {
this.guide_id = guide_id;
}
public String getPost_title() {
return post_title;
}
public void setPost_title(String post_title) {
this.post_title = post_title;
}
public String getPost_desc() {
return post_desc;
}
public void setPost_desc(String post_desc) {
this.post_desc = post_desc;
}
public String getPost_address() {
return post_address;
}
public void setPost_address(String post_address) {
this.post_address = post_address;
}
public byte[] getPost_image() {
return post_image;
}
public void setPost_image(byte[] post_image) {
this.post_image = post_image;
}
}
activity_main.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="com.ugurcangursen.guideappsqlite.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/app_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:padding="10dp"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_post.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="com.ugurcangursen.guideappsqlite.PostActivity">
<ImageButton
android:id="#+id/imageSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:background="#00ffffff"
android:scaleType="centerCrop"
app:srcCompat="#drawable/add_btn" />
<EditText
android:id="#+id/titleField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageSelect"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Title..."
android:inputType="textPersonName"
android:padding="10dp"
android:singleLine="true" />
<EditText
android:id="#+id/descField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/titleField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Description..."
android:inputType="textMultiLine"
android:padding="10dp" />
<EditText
android:id="#+id/addressField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/descField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Adres..."
android:inputType="textMultiLine"
android:padding="10dp" />
<Button
android:id="#+id/submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#color/colorPrimary"
android:text="SUBMIT POST"
android:textColor="#android:color/white" />
</RelativeLayout>
guide_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/post_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
app:srcCompat="#drawable/add_btn" />
<TextView
android:id="#+id/post_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:textSize="16dp"
android:textStyle="bold"
tools:text="Başlık" />
<TextView
android:id="#+id/post_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
tools:text="Açıklama" />
<TextView
android:id="#+id/post_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
tools:text="Adres" />
</LinearLayout>
</android.support.v7.widget.CardView>
I'm not reviewing all the code you have posted. However, it does appear that you are setting the adpater with an empty source (guides), so it would then display nothing.
The following version of the onCreate method may result in the data being displayed
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideDB = new GuideDB(this);
guides = new ArrayList<>();
applist = (RecyclerView) findViewById(R.id.app_list);
applist.setHasFixedSize(true);
applist.setLayoutManager(new LinearLayoutManager(this));
//adapter = new GuideAdapter(this,guides); //<<<< MOVED
//applist.setAdapter(adapter); //<<<< MOVED
try {
Cursor cursor = guideDB.getGuides("SELECT * FROM GUIDE_LIST");
while (cursor.moveToNext()){
int guide_id = cursor.getInt(0);
String post_tile = cursor.getString(1);
String post_desc = cursor.getString(2);
String post_address = cursor.getString(3);
byte [] post_image = cursor.getBlob(4);
Guides g = new Guides(guide_id,post_tile,post_desc,post_address,post_image);
guides.add(g);}
}catch (Exception e){e.printStackTrace();}
adapter = new GuideAdapter(this,guides); //<<<< MOVED
applist.setAdapter(adapter); //<<<< MOVED
}
It crashes on this line: alListView.setAdapter(adapter); It worked all last night and I didn't make any changes... I made a few formatting changes, maybe I deleted something I shouldn't have.
package com.grumpy.multipages;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainPage extends AppCompatActivity {
AlDatabaseAdapter AlHelper;
private ListView alListView;
//AlHelper helper;
private static final String TAG = "MultiPages";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
AlHelper = new AlDatabaseAdapter(this);
//SQLiteDatabase db = AlHelper.getWritableDatabase();
String myHouses = LoadDB();
String[] values = myHouses.split("\n");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
//alListView.setAdapter(adapter);
alListView.setAdapter(adapter); // CRASHES HERE
Log.d(TAG, "Main Page ");
//Button myBtn = (Button)findViewById(R.id.button1_Button);
Button myBtn1 = (Button)findViewById(R.id.button1_Button);
myBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), AddHouse.class);
//intent.putExtra("refer", "Called from Main Page");
startActivity(intent);
}
});
}
private String LoadDB() {
// Need to get list of Houses from Database
Log.d(TAG, "Calling LoadDB ");
String myHouses = AlHelper.getData();
Log.d(TAG, "Returning From LoadDB ");
Log.d(TAG,myHouses);
return myHouses;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
// Layout page
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainPage">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnAddHouse"
android:id="#+id/button1_Button" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center_horizontal"
android:choiceMode="singleChoice"
android:clickable="true"
tools:listitem="#android:layout/simple_list_item_1" />
Before:
alListView.setAdapter(adapter); // CRASHES HERE
you should assign to alListView your widget, and from your code it looks like its null at above line.
So add:
alListView = (ListView)findViewById(R.id.listView);
This may be null pointer exception because you declared your Listview(i.e. alListView) but you missed to define it i.e alListView=(ListView)findviewById...
code and trying to set adapter in a null object reference where it crashed.
I am new to android development, was following a tutorial in order to get a better understanding about fragments, but after completing the tutorial when it comes to testing I encountered this particular problem after removing a few syntax errors. In the logcat I get "threadid=1: thread exiting with uncaught exception (group=0x40a7193" I've spent almost an entire working day on it, I've looked but it seems like the solution to this problem is dependent upon the source code, I've been on a number of links but everywhere there's some source code provided and I haven't found a solution for my problem so far, any help will be much appreciated. Here is My Code:
MainActivity.java:
package com.example.fragmentsexample;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements ToolbarFragments.ToolbarListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onButtonClick(int fontsize, String text) {
TextFragment textFragment =
(TextFragment) getSupportFragmentManager().findFragmentById(R.id.text_fragment);
textFragment.changeTextProperties(fontsize, text);
}
}
Here is TextFragment.java:
package com.example.fragmentsexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends Fragment {
private static TextView textview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.text_fragment, container,false);
textview=(TextView) view.findViewById(R.id.textView1);
return view;
}
public void changeTextProperties(int fontsize, String text){
textview.setTextSize(fontsize);
textview.setText(text);
}
}
Here is ToolbarFragments.java
package com.example.fragmentsexample;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ToolbarFragments extends Fragment {
private static int seekvalue=10;
private static EditText editText;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
activityCallback=(ToolbarListener) activity;
}
catch (Exception e){
throw new ClassCastException(activity.toString()+ "must implement ToolbarListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle SavedInstanceState){
View view=inflater.inflate(R.layout.toolbar_fragment, container, false);
editText=(EditText) view.findViewById(R.id.editText1);
final SeekBar seekbar=(SeekBar) view.findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this);
final Button button=(Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
public void buttonClicked(View v){
activityCallback.onButtonClick(seekvalue,editText.getText().toString());
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
seekvalue=progress;
}
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
Here is the activity_main.xml:
<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"
tools:context=".MainActivity" >
<fragment
android:id="#+id/toolbar_fragment"
android:name="com.example.fragmentexample.ToolbarFragments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/toolbar_fragment" />
<fragment
android:id="#+id/text_fragment"
android:name="com.example.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/text_fragment" />
</RelativeLayout>
Here is the text_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/fragtwo"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Here is the toolbar_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="#string/button"/>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1"
android:layout_marginTop="14dp" />
</RelativeLayout>
Any help any sort of help will be appreciated it is my second post here i apologize for a messy post