I don't know what I'm doing wrong. I was ready to migrate from listview to recyclerview and followed the syntax then it gives me an error of
"element == null" from my build output
Here's my Databasehelper file:
package com.revise;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String NAME_TABLE = "NAME_TABLE";
public static final String COL_ID = "COLUMN_ID";
public static final String COLUMN_NAME = "COLUMN_NAME";
public static final String COLUMN_PRICE = "COLUMN_PRICE";
public static final String COLUMN_QUANTITY = "COLUMN_QUANTITY";
public static final String COLUMN_TOTAL = "COLUMN_TOTAL";
//private static final int DATABASE_VERSION = 2;
public DataBaseHelper(#Nullable Context context) {
super(context, "item.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + NAME_TABLE + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_NAME + " TEXT, "
+ COLUMN_PRICE + " FLOAT, "
+ COLUMN_QUANTITY + " INT, "
+ COLUMN_TOTAL + " FLOAT)";
db.execSQL(createTableStatement);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+NAME_TABLE);
onCreate(db);
}
public boolean addOne(Product product){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, product.getName());
cv.put(COLUMN_PRICE, product.getPrice());
cv.put(COLUMN_QUANTITY, product.getQuantity());
cv.put(COLUMN_TOTAL, product.getTotal());
long insert = db.insert(NAME_TABLE, null, cv);
if(insert==-1){
return false;
}
else{ return true; }
}
public boolean deleteOne(Product product){
SQLiteDatabase db = this.getWritableDatabase();
String queryString = "DELETE FROM "+NAME_TABLE+" WHERE " +COLUMN_NAME+ "=" +product.getName();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
return true;
}else { return false; }
}
public List<Product> getEveryone(){
List<Product> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + NAME_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
do{
String name = cursor.getString(1);
float price = cursor.getFloat(2);
int quantity = cursor.getInt(3);
Product newProduct = new Product(name, price, quantity);
returnList.add(newProduct);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return returnList;
}
}
Here's my RecyclerViewAdapter:
package com.revise;
import android.content.Context;
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 java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
List<Product> productList;
Context context;
public RecyclerViewAdapter(List<Product> productList, Context context) {
this.productList = productList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//itemlayout is the name of the layout that we are gonna be using
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemlayout,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
holder.tv_name.setText(productList.get(position).getName());//tv_name
holder.tv_price.setText(String.valueOf(productList.get(position).getPrice()));
holder.tv_qty.setText(String.valueOf(productList.get(position).getQuantity()));
holder.tv_total.setText(String.valueOf(productList.get(position).getTotal()));
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
//variables from my itemlayout
TextView tv_name, tv_price, tv_qty, tv_total;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = itemView.findViewById(R.id.tv_name);
tv_price = itemView.findViewById(R.id.tv_price);
tv_qty = itemView.findViewById(R.id.tv_qty);
tv_total = itemView.findViewById(R.id.tv_total);
}
}
}
The activity that is configuring the buttons:
package com.revise;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DataActivity extends AppCompatActivity {
Button bt_add;
EditText et_name, et_price, et_qty;
DataBaseHelper myDb;
List<Product> productList = new ArrayList<Product>();
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_add = findViewById(R.id.bt_add);
et_name = findViewById(R.id.et_name);
et_price = findViewById(R.id.et_price);
et_qty = findViewById(R.id.et_qty);
//lv_itemlist = findViewById(R.id.lv_itemlist);
myDb = new DataBaseHelper(DataActivity.this);
fillProductList(myDb);
bt_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Product p = new Product();
try {
p.setName(et_name.getText().toString());
p.setPrice(Float.parseFloat(et_price.getText().toString()));
p.setQuantity(Integer.parseInt(et_qty.getText().toString()));
} catch (Exception e){
Toast.makeText(DataActivity.this,"Exception:"+e,Toast.LENGTH_SHORT).show();
}
DataBaseHelper dataBaseHelper = new DataBaseHelper(DataActivity.this);
dataBaseHelper.addOne(p);
}
});
recyclerView = findViewById(R.id.lv_itemlist);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(DataActivity.this);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new RecyclerViewAdapter(productList, DataActivity.this);
recyclerView.setAdapter(mAdapter);
}
private void fillProductList(DataBaseHelper myDb) {
productList.addAll(myDb.getEveryone());
}
}
and it's corresponding xml file:
<?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=".DataActivity">
<EditText
android:id="#+id/et_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/et_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="numberDecimal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/et_name" />
<EditText
android:id="#+id/et_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/et_price" />
<Button
android:id="#+id/bt_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.189"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/et_qty" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/lv_itemlist"
android:layout_width="384dp"
android:layout_height="456dp"
android:layout_marginTop="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bt_add" />
</androidx.constraintlayout.widget.ConstraintLayout>
One thing I notice is your mAdapter is of type RecyclerView.Adapter not RecyclerViewAdapter.
There are a bunch of videos and articles on working with recycler views that I suggest you watch. Also start using Androids Room library. It's the recommended way to work with SQLite. There is a codelab for it, I believe called Room with a View.
Related
sorry in adavaced bcz i am first time askking question on stack flow so and if need any other please let me know
okk my firestore Collestion is like these collection("user").document(currentUserId).collection("AddBlog").document
and i need AddBlog document and last my field name of firestore is same to model.java variable
code of activity name Trial.java
package com.example.talkvirtual;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class TrialActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Model> dataList;
FirebaseFirestore db;
FirebaseAuth mAuth;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trial);
recyclerView = findViewById(R.id.recyclerViewTrial);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dataList = new ArrayList<>();
recyclerView.setAdapter(myAdapter);
myAdapter = new MyAdapter(dataList,this);
db = FirebaseFirestore.getInstance();
mAuth= FirebaseAuth.getInstance();
String currentUserId = mAuth.getCurrentUser().getUid();
db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Model model = d.toObject(Model.class);
dataList.add(model);
}
myAdapter.notifyDataSetChanged();
}
});
}
}
code of adpater class name MyAdapter.java
package com.example.talkvirtual;
import android.content.Context;
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 java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
public MyAdapter(ArrayList<Model> listblogProfile, Context context) {
this.ListblogProfile = listblogProfile;
this.context = context;
}
private ArrayList<Model> ListblogProfile;
private Context context;
// private ShowActivity activity;
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.container_blog, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
Model model = ListblogProfile.get(position);
holder.blogTitleTv.setText(model.getBlogTitle());
holder.blogContentTv.setText(model.getBlogContent());
}
#Override
public int getItemCount() {
return ListblogProfile.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView blogTitleTv, blogContentTv;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
blogContentTv = itemView.findViewById(R.id.blogContentContainer);
blogTitleTv = itemView.findViewById(R.id.getTitleContainer);
}
}
}
code of my cardView xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layoutNote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?attr/selectableItemBackgroundBorderless"
app:cardElevation="8dp"
android:layout_margin="10dp"
android:background="#color/light_dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/getTitleContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:textColor="#color/textColor"
android:textSize="24dp"
android:textStyle="bold"
android:padding="10dp"
/>
<TextView
android:id="#+id/blogContentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="100dp"
android:textColor="#color/textColor"
android:hint="Blog Content"
android:textColorHint="#color/gray"
android:textSize="20dp"
android:padding="10dp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
code of model class
package com.example.talkvirtual;
public class Model {
String blogTitle;
String blogContent;
String id;
public Model(){}//empty constructor is neccessary firebase
public Model(String blogTitle, String blogContent, String id) {
this.blogTitle = blogTitle;
this.blogContent = blogContent;
this.id = id;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I think There are two mistake
1.Your adapter does not have the valid value
when you set it for the recyclerview
2.Your data is null because you don't add any member to it as well as the adapter.
db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Model model = d.toObject(Model.class);
dataList.add(model);
}
myAdapter.notifyDataSetChanged();
}
});
myAdapter = new MyAdapter(dataList,this);
recyclerView.setAdapter(myAdapter);
I guess this should be work.
When the user logins an activity where the user can create their account opens (CreateProfileActivity). When the profile is created the user is redirected to the recyclerView activity where their profile info is displayed in a recyclerView. When user clicks on the item in recyclerView the Update Activity will open. I want their profile information from the recyclerView to load on the Update Activity. Please help.
P.S. Since I haven't made the CreateProfile_Activity open only once, as I don't want the user to create more than one profile, So for now: I ran the app once and created an account and then I changed it so now when the user logins it opens the recyclerView_Activity.
Here is the recyclerView_Activity
package com.example.insert_update_activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class recyclerView_Activity extends AppCompatActivity {
// Button insertBtn;
RecyclerView recyclerView;
DBHelper myDB;
ArrayList<String> temp_id, temp_name, temp_age;
myAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
/* insertBtn = (Button) findViewById(R.id.insertBtn);
insertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(recyclerView_Activity.this, Insert_Activity.class);
startActivity(intent);
}
});*/
myDB = new DBHelper(recyclerView_Activity.this);
temp_id = new ArrayList<>();
temp_name = new ArrayList<>();
temp_age = new ArrayList<>();
storeDataInArrays();
myAdapter = new myAdapter(recyclerView_Activity.this, this, temp_id, temp_name, temp_age);
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView_Activity.this));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
{
recreate();
}
}
void storeDataInArrays() {
Cursor cursor = myDB.readData(); // Cursor cursor = myDB.readAllData();
if (cursor.getCount() == 0)
{
Toast.makeText(recyclerView_Activity.this, "No Data", Toast.LENGTH_SHORT).show();
}
else
{
while (cursor.moveToNext()) {
temp_id.add(cursor.getString(0));
temp_name.add(cursor.getString(1));
temp_age.add(cursor.getString(2));
}
}
}
}
Here is the UpdateActivity
package com.example.insert_update_activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class Update_Activity extends AppCompatActivity {
EditText name, age;
Button updateBtn;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
name = (EditText) findViewById(R.id.edit_name);
age = (EditText) findViewById(R.id.edit_age);
updateBtn = (Button) findViewById(R.id.updateBtn);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sName = name.getText().toString().trim();
String sAge = age.getText().toString().trim();
DBHelper db = new DBHelper(Update_Activity.this);
db.updateData(id, sName, sAge);
Intent intent = new Intent(Update_Activity.this, com.example.insert_update_activity.recyclerView_Activity.class);
startActivity(intent);
}
});
getAndSetIntentData();
}
void getAndSetIntentData() {
if (getIntent().hasExtra("id") && getIntent().hasExtra("Name") && getIntent().hasExtra("Age"))
{
// Getting data from Intent
id = getIntent().getStringExtra("id");
String NAME = getIntent().getStringExtra("Name");
String AGE = getIntent().getStringExtra("Age");
// Setting Intent Data
name.setText(NAME);
age.setText(AGE);
}
else
{
Toast.makeText(Update_Activity.this, "No Data", Toast.LENGTH_SHORT).show();
}
}
}
Here is the DBHelper
package com.example.insert_update_activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "Database.db";
private static final int DATABASE_VERSION = 1;
// Create table
private static final String TABLE_TEMP = "TEMPP";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";
public DBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String profileQuery = "CREATE TABLE " + TABLE_TEMP +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " + COLUMN_AGE + " INTEGER " + ")";
db.execSQL(profileQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEMP);
onCreate(db);
}
// Functions for TEMP TABLE ******************************************************************************************************************************************** PROFILE TEMP
public Boolean insertData(String name, String age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, name);
cv.put(COLUMN_AGE, age);
long result = db.insert(TABLE_TEMP, null, cv);
if (result == -1) {
Toast.makeText(context, "Failed to Insert", Toast.LENGTH_SHORT).show();
return false;
} else {
Toast.makeText(context, "Data Inserted Successfully!", Toast.LENGTH_SHORT).show();
return true;
}
}
Cursor readData() {
String query = "SELECT * FROM " + TABLE_TEMP;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if (db != null) {
cursor = db.rawQuery(query, null);
}
return cursor;
}
// Update data using where clause;
public Boolean updateData(String row_id, String name, String age)
{
SQLiteDatabase db = this.getWritableDatabase(); // SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, name);
cv.put(COLUMN_AGE, age);
long result = db.update(TABLE_TEMP, cv, COLUMN_ID + " =? ", new String[]{row_id});
if (result == -1)
{
Toast.makeText(context, "Failed to Update", Toast.LENGTH_SHORT).show();
return false;
}
else
{
Toast.makeText(context, "Successfully Updated!", Toast.LENGTH_SHORT).show();
return true;
}
}
}
Here is the Adapter
package com.example.insert_update_activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class myAdapter extends RecyclerView.Adapter<myAdapter.MyViewHolder> {
private Context context;
Activity activity;
private ArrayList id, name, age;
myAdapter(Activity activity, Context context, ArrayList id, ArrayList name, ArrayList age) {
this.activity = activity;
this.context = context;
this.id = id;
this.name = name;
this.age = age;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.id_txt.setText(String.valueOf(id.get(position)));
holder.name_txt.setText(String.valueOf(name.get(position)));
holder.age_txt.setText(String.valueOf(age.get(position)));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Update_Activity.class);
intent.putExtra("id", String.valueOf(id.get(position)));
intent.putExtra("name", String.valueOf(name.get(position)));
intent.putExtra("age", String.valueOf(age.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id_txt, name_txt, age_txt;
LinearLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id_txt = itemView.findViewById(R.id.id_txt);
name_txt = itemView.findViewById(R.id.name_txt);
age_txt = itemView.findViewById(R.id.age_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
And here is the xml file my_row for the recyclerView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
android:orientation="vertical"
android:id="#+id/mainLayout">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:outlineSpotShadowColor="#000000"
app:cardElevation="3dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp">
<TextView
android:id="#+id/id_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="1"
android:textColor="#9A9797"
android:textSize="35dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/nameTitle"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="NAME:"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ageTitle"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="AGE:"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="#+id/nameTitle"
app:layout_constraintTop_toBottomOf="#+id/nameTitle" />
<TextView
android:id="#+id/name_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="15sp"
app:layout_constraintStart_toEndOf="#+id/nameTitle"
app:layout_constraintTop_toTopOf="#+id/nameTitle" />
<TextView
android:id="#+id/age_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age"
android:textSize="15sp"
app:layout_constraintStart_toEndOf="#+id/ageTitle"
app:layout_constraintTop_toBottomOf="#+id/nameTitle" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
The login activity is pretty simple. It just allows the user to login if username == "User1" and password == "123456".
The CreateProfile_Activity just uses the insertData once
Okay so now it works. I'm not sure this is why, but I will post the changes I made.
So one problem was in myAdapter. In the mainLayout OnClick the "name" and "age" where different from the "Name" and "Age" in the UpdateActivity where I get data from Intent. The first letters of both 'age' and 'name' were not in CAPITALS.
Another thing I changed was the get(position) in the onBindHolder.
Now the onBindHolder looks like this:
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.id_txt.setText(String.valueOf(id.get(holder.getAdapterPosition())));
holder.name_txt.setText(String.valueOf(name.get(holder.getAdapterPosition())));
holder.age_txt.setText(String.valueOf(age.get(holder.getAdapterPosition())));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Update_Activity.class);
intent.putExtra("id", String.valueOf(id.get(holder.getAdapterPosition())));
intent.putExtra("Name", String.valueOf(name.get(holder.getAdapterPosition())));
intent.putExtra("Age", String.valueOf(age.get(holder.getAdapterPosition())));
v.getContext().startActivity(intent);
//activity.startActivityForResult(intent, 1);
}
});
}
Hope it helps anyone
i'm new to java and android(programmed in C# before).
i'm trying to populate a listview with a custom layout but nothing happens.
the listview is in the main activity and is being updated from a separate class.
here is all the stuff that i am trying to find the problem in:
activity_main.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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nasir.pre_alpha.MainActivity"
android:orientation="vertical">
<Button
android:text="Get Messages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/msg_list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:onClick="onClick" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="15dp"
android:layout_below="#+id/msg_list"
android:id="#+id/msg_listview" />
</RelativeLayout>
list_view_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearlayout">
<TextView
android:text="Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView" />
<TextView
android:text="NUMBER"
android:layout_width="171dp"
android:layout_height="wrap_content"
android:id="#+id/txt_number" />
<TextView
android:text="Message Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3" />
<TextView
android:text="TEXT"
android:layout_height="wrap_content"
android:id="#+id/txt_msg"
android:layout_width="171dp" />
</LinearLayout>
MainActivity.java:
package com.nasir.pre_alpha;
import android.Manifest;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.READ_SMS},255);
}
public void onClick (View l){
ContentResolver rslv=getContentResolver();
final String[] p=new String[]{"*"};
Uri uri=Uri.parse("content://sms");
Cursor cursor=rslv.query(uri,p,null,null,null);
cursor.moveToFirst();
ArrayList<String> numbers=new ArrayList<>();
ArrayList<String> msg_body=new ArrayList<>();
while (cursor.moveToNext()){
numbers.add(cursor.getString(cursor.getColumnIndex("address")));
msg_body.add(cursor.getString(cursor.getColumnIndex("body")));
}
model m=new model();
view v=new view();
controller c=new controller(m,v,getApplicationContext());
c.set_data(numbers,msg_body);
c.view_data();
}
}
model.java:
package com.nasir.pre_alpha;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class model {
private ArrayList<String> numbers=new ArrayList<>();
private ArrayList<String> msg_body=new ArrayList<>();
public ArrayList<String> get_numbers(){
return numbers;
}
public ArrayList<String> getMsg_body(){
return msg_body;
}
public void set_numbers(ArrayList<String> numbers){
this.numbers=numbers;
}
public void set_Msgbody(ArrayList<String> msg_body){
this.msg_body=msg_body;
}
}
view.java:
package com.nasir.pre_alpha;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class view {
private Context c;
private class viewadapter extends BaseAdapter{
private ArrayList<String> numbers=new ArrayList<>();
private ArrayList<String> msg_body=new ArrayList<>();
public viewadapter(ArrayList<String> numbers,ArrayList<String> msg_body){
this.numbers=numbers;
this.msg_body=msg_body;
}
public int getCount(){
return numbers.size();
}
public View getView(int pos, View view, ViewGroup viewGroup){
LayoutInflater inflater=(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.list_view_layout,null);
TextView number=(TextView)row.findViewById(R.id.txt_number);
number.setText(numbers.get(pos));
TextView msg_body=(TextView)row.findViewById(R.id.txt_msg);
Toast.makeText(c,msg_body.getText(),Toast.LENGTH_SHORT).show();
msg_body.setText(this.msg_body.get(pos));
return row;
}
public long getItemId(int pos){
return pos;
}
public Object getItem(int arg){
return null;
}
}
void set_context(Context context){
c=context;
}
public void update_data(ArrayList<String> numbers,ArrayList<String> msg_body){
viewadapter adapter=new viewadapter(numbers,msg_body);
LayoutInflater inflater=(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v=inflater.inflate(R.layout.activity_main,null);
ListView lst=(ListView)v.findViewById(R.id.msg_listview);
lst.setAdapter(adapter);
}
}
controller.java:
package com.nasir.pre_alpha;
import android.content.Context;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class controller {
private model m;
private view v;
private Context c;
public controller(model m,view v,Context c){
this.m=m;
this.v=v;
this.c=c;
}
public void set_data(ArrayList<String> numbers,ArrayList<String> msg_body){
this.m.set_numbers(numbers);
this.m.set_Msgbody(msg_body);
}
public void view_data(){
v.set_context(c);
v.update_data(m.get_numbers(),m.getMsg_body());
}
}
but i can't find the problem.
the listview is just empty(won't show up)
You didn't initialize the listview and you haven't assigned a list of items to it. Try:
ListView listview = (ListView) findViewById(R.id.msg_listview);
listview.setAdapter(.......);
I really can't understand your code. I'd suggest you do it like this:
add this:
<uses-permission android:name="android.permission.READ_CONTACTS" />
in your manifest instead of:
ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.READ_SMS},255);
MainActivity
public class MainActivity extends AppCompatActivity {
private ArrayList<model> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewadapter adapter = new viewadapter(list, getApplicationContext());
ListView lst = (ListView) findViewById(R.id.msg_listview);
lst.setAdapter(adapter);
}
public void onClick (View l){
ContentResolver rslv = getContentResolver();
final String[] p = new String[]{"*"};
Uri uri = Uri.parse("content://sms");
Cursor cursor = rslv.query(uri, p, null, null, null);
cursor.moveToFirst();
while (cursor.moveToNext()){
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndex("body"));
model m = new model();
m.setNumbers(address);
m.setMsgbody(body);
list.add(m);
}
}
}
model
public class model {
String numbers;
String msg_body;
public String getNumbers(){
return numbers;
}
public String getMsg_body(){
return msg_body;
}
public void setNumbers(String numbers){
this.numbers = numbers;
}
public void setMsgbody(String msg_body){
this.msg_body = msg_body;
}
}
viewadapter
private class viewadapter extends BaseAdapter{
private ArrayList<model> list = new ArrayList<>();
private Context context;
public viewadapter(ArrayList<model> list, Context context){
this.list = list;
this.context = context;
}
public int getCount(){
return list.size();
}
public View getView(int pos, View view, ViewGroup viewGroup){
View row = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_view_layout, null);
model model = list.get(pos)
TextView number = (TextView) row.findViewById(R.id.txt_number);
number.setText(model.getNumbers);
TextView msg_body = (TextView) row.findViewById(R.id.txt_msg);
Toast.makeText(c, msg_body.getText(), Toast.LENGTH_SHORT).show();
msg_body.setText(model.getMsg_body());
return row;
}
public long getItemId(int pos){
return pos;
}
public Object getItem(int arg){
return list.get(arg);
}
}
}
I don't think there is any need for a controller class.
I'm new to android and I managed to insert data from EditText into database and I show it into ListView, but now I need to show a single note when clicked on item inside ListView and I just don't know how. I want it to be editable in activity_edit_note.xml .Can someone please help me? Here is my code.
Notes.java
package com.cidecode.xnotes;
public class Notes {
private long id;
private String title;
private String note;
private String date;
public Notes(){
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString(){
return title + "\t" + date + "\n" + note;
}
}
DatabaseHelper.java
package com.cidecode.xnotes;
import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String TABLE_NOTES = "notes";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_NOTE = "note";
public static final String COLUMN_DATE = "date";
private static final String DATABASE_NAME = "xnotes.db";
private static final int DATABASE_VERSION = 1;
// Create the database
private static final String DATABASE_CREATE = "create table " + TABLE_NOTES + "(" +
COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE + " text not null, " +
COLUMN_NOTE + " text not null, " + COLUMN_DATE + " text not null);";
// Drop table notes
private static final String DATABASE_DROP_TABLE_NOTES = "drop table if exists " + TABLE_NOTES;
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(android.database.sqlite.SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(android.database.sqlite.SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseHelper.class.getName(), "Upgrading database from v" + oldVersion + " to v" +
newVersion + " which will delete all old data.");
db.execSQL(DATABASE_DROP_TABLE_NOTES);
onCreate(db);
}
}
NotesDataSource.java
package com.cidecode.xnotes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.EditText;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class NotesDataSource {
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private String[] allColumns = {DatabaseHelper.COLUMN_ID, DatabaseHelper.COLUMN_TITLE, DatabaseHelper.COLUMN_NOTE, DatabaseHelper.COLUMN_DATE};
public NotesDataSource(Context context){
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException{
database = dbHelper.getWritableDatabase();
}
public void close(){
dbHelper.close();
}
public Notes createNote(String title, String note, String date){
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_TITLE, title);
values.put(DatabaseHelper.COLUMN_NOTE, note);
values.put(DatabaseHelper.COLUMN_DATE, date);
long insertId = database.insert(DatabaseHelper.TABLE_NOTES, null, values);
Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
DatabaseHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
Notes newNotes = cursorToNote(cursor);
cursor.close();
return newNotes;
}
public List<Notes> getAllNotes(){
List<Notes> notesList = new ArrayList<Notes>();
Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
Notes note = cursorToNote(cursor);
notesList.add(note);
cursor.moveToNext();
}
cursor.close();
return notesList;
}
private Notes cursorToNote(Cursor cursor){
Notes note = new Notes();
note.setId(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setNote(cursor.getString(2));
note.setDate(cursor.getString(3));
return note;
}
public void deleteNote(int id){
database.delete(DatabaseHelper.TABLE_NOTES, DatabaseHelper.COLUMN_ID + "=" + id, null);
}
}
AddNote.java
package com.cidecode.xnotes;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.SQLException;
public class AddNote extends ActionBarActivity {
private EditText title = null;
private EditText note = null;
private String s_title, s_note, s_date;
Button b_save;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private NotesDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
dbHelper = new DatabaseHelper(this);
datasource = new NotesDataSource(this);
try {
datasource.open();
} catch (SQLException e) {
e.printStackTrace();
}
title = (EditText)findViewById(R.id.id_title);
note = (EditText)findViewById(R.id.id_write_note_here);
s_title = title.getText().toString();
s_note = note.getText().toString();
s_date = "21.11.1111";
b_save = (Button)findViewById(R.id.id_save);
b_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datasource.createNote(title.getText().toString(), note.getText().toString(), s_date);
Toast.makeText(getApplicationContext(), "Note is saved.", Toast.LENGTH_LONG).show();
Log.w("Title: ", title.getText().toString());
Log.w("Note: ", note.getText().toString());
Log.w("Date: ", s_date);
Intent intent = new Intent(AddNote.this, MainActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_add_note.xml
<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:orientation="vertical"
tools:context=".MainActivity"
android:background="#EBD28F">
<TextView
android:id="#+id/id_add_new_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/s_add_new_note"
android:gravity="center"
android:textSize="30sp"
android:layout_marginBottom="10dp"/>
<EditText
android:id="#+id/id_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/s_title"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"/>
<EditText
android:id="#+id/id_write_note_here"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:hint="#string/s_write_note_here"
android:gravity="top" />
<Button
android:id="#+id/id_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="#string/s_save"
android:textColor="#FFFFFF"
android:background="#5E553A"/>
</LinearLayout>
MainActivity.java
package com.cidecode.xnotes;
import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.sql.SQLException;
import java.util.List;
public class MainActivity extends ListActivity {
Button AddNew;
private ListView listView;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private NotesDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DatabaseHelper(this);
datasource = new NotesDataSource(this);
try {
datasource.open();
} catch (SQLException e) {
e.printStackTrace();
}
List<Notes> values = datasource.getAllNotes();
final ArrayAdapter<Notes> adapter = new ArrayAdapter<Notes>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return false;
}
});
AddNew = (Button)findViewById(R.id.id_add_new);
AddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddNote.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<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:orientation="vertical"
tools:context=".MainActivity"
android:background="#EBD28F">
<TextView
android:id="#+id/id_xnotes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/s_xnotes"
android:gravity="center"
android:textSize="30sp"
android:layout_marginBottom="10dp"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:clickable="true"
android:longClickable="true"></ListView>
<Button
android:id="#+id/id_add_new"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="#string/s_add_new"
android:textColor="#FFFFFF"
android:background="#5E553A"/>
</LinearLayout>
EditNote.java
package com.cidecode.xnotes;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class EditNote extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_edit_note.xml
<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:orientation="vertical"
tools:context=".MainActivity"
android:background="#EBD28F">
<TextView
android:id="#+id/id_add_new_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/s_edit_note"
android:gravity="center"
android:textSize="30sp"
android:layout_marginBottom="10dp"/>
<EditText
android:id="#+id/id_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/s_title"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"/>
<EditText
android:id="#+id/id_write_note_here"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:hint="#string/s_write_note_here"
android:gravity="top" />
<Button
android:id="#+id/id_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="#string/s_save"
android:textColor="#FFFFFF"
android:background="#5E553A"/>
</LinearLayout>
Its a method to get single note by COLUMN_ID
public Notes getSingleNote(long id){
Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
COLUMN_ID +"=?", new String[]{String.valueOf(id)}, null, null, null);
Note note = null;
if(cursor.moveToFirst())
note = cursorToNote(cursor);
cursor.close();
return note;
}
Declare List<Notes> values globally. And update your listView item click listener like below mentioned:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Notes selectedNote = values.get(position);
}
});
Here "selectedNote" selected item. And pass this item by following the below link.
How do I pass an object from one activity to another on Android?
I tried all possible cases but data is not showing in the list from database.my starting activity have list view which is to be empty in starting and when user fill the data and save it from another activity,ans press back button the data should be shown in the first activity which have list view.,but every time data is not show
MainActivty.java
package com.example.smscampaign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class Campaign_Details extends Activity {
private Demo selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_demostration);
TextView text1=(TextView) findViewById(R.id.text1);
TextView text2=(TextView) findViewById(R.id.text1);
DataBaseHandler info= new DataBaseHandler(this);
info.open();
String data=info.getData();
info.close();
String[] values= new String[]{ data };
//txt.setText(data);
// Button next=(Button) findViewById(R.id.next);
// Map<String, String[]> storage = new HashMap<String, String[]>();
// String[] tableItems = storage.get("ContactTable");
// next.setOnClickListener(this);
// final ListView listview = (ListView) findViewById(R.id.listview);
ListView listview1 = (ListView) findViewById(R.id.listview1);
// TextView emptyText = (TextView)findViewById(android.R.id.empty);
//listview.setEmptyView(findViewById(R.id.empty));
// TextView emptyText = (TextView)findViewById(android.R.id.empty);
// listview .setEmptyView(emptyText);
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
selectedAdapter = new Demo(this,values);
ListView listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(selectedAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent n = new Intent(getApplicationContext(), SmsSend.class);
startActivity(n);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.nextPage:
Intent i = new Intent(this,SmsSend.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
demo.java
package com.example.smscampaign;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Demo extends ArrayAdapter{
private Campaign_Details list1;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Demo(Context context, String[] values) {
super(context, R.layout.list);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.data);
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.data);
text1.setText(values[position]);
return v;
}
}
activity_list_demonstration.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:stretchColumns="3" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textcolour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="#drawable/green_circle" />
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10dp"
android:text="Active Campaign"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#4AE56B" />
<TextView
android:id="#+id/textnum1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="130dp"
android:background="#drawable/green_badge"
android:gravity="center"
android:text=" 0 "
android:textColor="#color/white" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="240dp"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:stretchColumns="3" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textcolour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="#drawable/grey_circle" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="Closed Campaign"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textnum2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="130dp"
android:background="#drawable/grey_badge"
android:gravity="center"
android:text=" 0 "
android:textColor="#color/white" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="140dp"
android:orientation="vertical" >
<ListView
android:id="#+id/listview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text" >
</TextView>
</LinearLayout>
DatabaseHandler.java// databaseclass
package com.example.smscampaign;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandler{
public static final String KEY_ROWID="_id";
public static final String KEY_NAME="person_name";
public static final String KEY_SCALE="scale_person";
private static final String DATABASE_NAME="Scaledb";
private static final String DATABASE_TABLE="peopleTable";
private static final int DATABASE_VERSION=1;
private DbHelper ourHepler;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_SCALE + " TEXT NOT NULL );"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
onCreate(db);
}
}
public DataBaseHandler(Context c){
ourContext=c;
}
public DataBaseHandler open() throws SQLException{
ourHepler = new DbHelper(ourContext);
ourDatabase= ourHepler.getWritableDatabase();
return this;
}
public void close()
{
ourHepler.close();
}
public long entryCreate(String name, String scale) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_SCALE, scale);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col, null, null, null, null, null);
String run="";
int iRow=c.getColumnIndex(KEY_ROWID);
int iName=c.getColumnIndex(KEY_NAME);
int iScale=c.getColumnIndex(KEY_SCALE);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
run=run+c.getString(iRow)+ " " + c.getString(iName) + " " + c.getString(iScale) + "\n";
}
return run;
}
public String getScale(long l) {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col,KEY_ROWID + "-" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String scale=c.getString(2);
return scale;
}
return null;
}
public String getName(long l) {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col,KEY_ROWID + "-" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String name=c.getString(1);
return name;
}
return null;
}
public void updateEntry(long lt, String mName, String mScale) {
// TODO Auto-generated method stub
ContentValues cvUpdate=new ContentValues();
cvUpdate.put(KEY_NAME,mName);
cvUpdate.put(KEY_SCALE,mScale);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "-" + lt, null);
}
public void deleteEntry(long ltt) throws SQLException{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + ltt,null);
}
}
You need to change at some places. You have declared your arraylist globally as a
private ArrayList<String> list;
after that again you have declared on onCreate() method
final ArrayList<String> list = new ArrayList<String>();
So replace that by
list = new ArrayList<String>();
Now in your all data is added in your list but in your adapter you have passed values string array. So you also need to change from
selectedAdapter = new Demo(this,values);
to
selectedAdapter = new Demo(this,list);
Change the getview method contents.
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.data);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
Also if you are not customizing layout[using only a textview] use the arrayadapter straightaway by choosing default layout.
in your ArrayAdapter you wrote
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
} else
v = convertView;
Remove the else statement. or rather remove the complete if-else statement. Also
TextView text1 = (TextView) v.findViewById(R.id.data); is extra you have already defined this specific TextView in label
EDIT
public Demo(Context context, String[] values) {
super(context, R.layout.list);
this.context = context;
this.values = values;
}
to
public Demo(Context context, String[] values) {
super(context, R.layout.list,values);
this.context = context;
this.values = values;
}
press back button the data should be shown in the first activity
You write your database loading code in onCreate() method which executes once in its life-cycle i.e when your application starts or when activity destroyed like in orientation changes.
So when you press back button the onCreate() has not called and the same will be continue with list.
Some suggessions:
its good if you write all database stuff in your onResume()
otherwise call finish() in your onPause() method of your main activity and again start it through intent in back pressed method of your second_activity..finish() kills the activity when you go to next one ..and again recreate when you come from the second through strtaActivity followed by its corresponding intent.
And also its better if you use StringTokenizer when you get data from database and put into String array.