In in the notes portion of my app i get the error "Unresolved reference: valueOf" in my EquipmentTrackerAllnotes.kt file.
the way my app operates is when you open the app initially it opens up to the dashboard the main home screen, then there is a navigation drawer on the side. One of the fragments in the navigation drawer is my "EquipmentTracker" aka the area where you can make notes of equipment the user may have. In side there you can add notes, delete and edit.
I'm open ears to any recommendations on possible changes i should make as well. But for now my main focus is fixing this error listed above.
EquipmentTracker.kt
package com.example.mechanicsapp
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.mechanicsapp.Model.noteModel
import com.example.mechanicsapp.database.MySqliteHelper
import com.example.mechanicsapp.databinding.FragmentEquipmentTrackerBinding
class EquipmentTracker : Fragment() {
private var _binding: FragmentEquipmentTrackerBinding? = null
private val binding get() = _binding!!
var intent = Intent(requireContext(), EquipmentTracker::class.java)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
//return inflater.inflate(R.layout.sign_in_fragment, container, false)
// Inflate the layout for this fragment
_binding = FragmentEquipmentTrackerBinding.inflate(inflater, container, false)
binding.root
val helper = MySqliteHelper(requireContext())
binding.btnDisplay.setOnClickListener(View.OnClickListener {
intent = Intent(activity, FragmentEquipmentTrackerBinding::class.java)
startActivity(intent)
return#OnClickListener
})
binding.btnSave.setOnClickListener(View.OnClickListener {
val model = noteModel()
model.bumpernumber = binding.bumpernumber.text.toString()
model.description = binding.description.text.toString()
model.nsn = binding.nsn.text.toString()
model.serialnumber = binding.serialnumber.text.toString()
model.date = binding.date.text.toString()
if (model.bumpernumber.isEmpty()) {
binding.bumpernumber.error = "Enter bumper number"
return#OnClickListener
}
if (model.description.isEmpty()) {
binding.description.error = "Enter description"
return#OnClickListener
}
if (model.nsn.isEmpty()) {
binding.nsn.error = "Enter nsn"
return#OnClickListener
}
if (model.serialnumber.isEmpty()) {
binding.serialnumber.error = "Enter serial number"
return#OnClickListener
}
if (model.date.isEmpty()) {
binding.date.error = "Enter date"
return#OnClickListener
}
val r = helper.saveNote(model)
if (r) {
Toast.makeText(context, "note is saved", Toast.LENGTH_SHORT)
.show()
} else {
Toast.makeText(context, "some thing want wrong", Toast.LENGTH_SHORT)
.show()
}
})
return binding.root
}
}
EquipmentTrackerAllnotes.kt
package com.example.mechanicsapp
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.mechanicsapp.Model.noteModel
import com.example.mechanicsapp.adapter.NoteAdapter
import com.example.mechanicsapp.database.MySqliteHelper
import com.example.mechanicsapp.databinding.ActivityEquipmentTrackerAllnotesBinding
#Suppress("NAME_SHADOWING")
class EquipmentTrackerAllnotes : AppCompatActivity() {
private var adapter: NoteAdapter? = null
private var binding: ActivityEquipmentTrackerAllnotesBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEquipmentTrackerAllnotesBinding.inflate(layoutInflater)
setContentView(binding!!.root)
fetchNotes()
}
private fun fetchNotes() {
val helper = MySqliteHelper(this)
adapter = NoteAdapter(this, helper.allNotes)
adapter!!.setOnNoteItemClickListener(object : NoteAdapter.OnNoteItemClickListener {
override
fun Onclick(model: noteModel) {
val builder = AlertDialog.Builder(this#EquipmentTrackerAllnotes)
builder.setTitle("Important")
builder.setMessage("Are your sure?")
builder.setPositiveButton("Yes" ) {
dialogInterface, _ ->
val helper = MySqliteHelper(this#EquipmentTrackerAllnotes)
val check = helper.delNoteById(String.valueOf(model.id))
if (check) {
fetchNotes()
Toast.makeText(this#EquipmentTrackerAllnotes, "Deleted", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(
this#EquipmentTrackerAllnotes,
"something went wrong",
Toast.LENGTH_SHORT
).show()
}
dialogInterface.dismiss()
}.setNegativeButton(
"No"
) { dialogInterface, _ -> dialogInterface.dismiss() }
builder.create().show()
}
override fun OnEdit(model: noteModel) {
val builder = AlertDialog.Builder(this#EquipmentTrackerAllnotes)
val view: View = LayoutInflater.from(this#EquipmentTrackerAllnotes)
.inflate(R.layout.edit_note, null, false)
val bm = view.findViewById<EditText>(R.id.bumpernumber)
val des = view.findViewById<EditText>(R.id.description)
val nsn = view.findViewById<EditText>(R.id.nsn)
val sn = view.findViewById<EditText>(R.id.serialnumber)
val date = view.findViewById<EditText>(R.id.date)
val btnUpdate = view.findViewById<Button>(R.id.btnUpdate)
bm.setText(model.bumpernumber)
des.setText(model.description)
nsn.setText(model.nsn)
sn.setText(model.serialnumber)
date.setText(model.date)
builder.setView(view)
val alertDialog = builder.create()
btnUpdate.setOnClickListener {
val model1 = noteModel()
model1.id = model.id
model1.bumpernumber = bm.text.toString()
model1.description = des.text.toString()
model1.nsn = nsn.text.toString()
model1.serialnumber = sn.text.toString()
model1.date = date.text.toString()
updateNote(model1)
alertDialog.dismiss()
}
alertDialog.show()
}
})
this.binding?.recyclerView?.setHasFixedSize(true)
this.binding?.recyclerView?.layoutManager = LinearLayoutManager(this)
this.binding?.recyclerView?.adapter = adapter
}
private fun updateNote(model: noteModel) {
val helper = MySqliteHelper(this#EquipmentTrackerAllnotes)
val check = helper.updateNoteById(model)
if (check) {
fetchNotes()
Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "something went wrong", Toast.LENGTH_SHORT).show()
}
}
}
in my adapter folder I have NoteAdapter.java
NoteAdapter.java
package com.example.mechanicsapp.adapter;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.mechanicsapp.Model.noteModel;
import com.example.mechanicsapp.R;
import com.example.mechanicsapp.database.MySqliteHelper;
import java.util.List;
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.viewHolder> {
List<noteModel> list;
Activity activity;
OnNoteItemClickListener listener;
public NoteAdapter(Activity activity,List<noteModel> list) {
this.list=list;
this.activity=activity;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.row_note,null,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
noteModel model=list.get(position);
holder.bumpernumber.setText(model.getBumpernumber());
holder.description.setText(model.getDescription());
holder.nsn.setText(model.getNsn());
holder.serialnumber.setText(model.getSerialnumber());
holder.date.setText(model.getDate());
holder.more.setOnClickListener(view -> {
PopupMenu menu=new PopupMenu(activity,holder.more);
menu.getMenuInflater().inflate(R.menu.more_menu,menu.getMenu());
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.edit:
listener.OnEdit(model);
break;
case R.id.delete:
listener.Onclick(model);
break;
}
return false;
}
});
menu.show();
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class viewHolder extends RecyclerView.ViewHolder{
TextView bumpernumber,description,nsn,serialnumber,date;
ImageView more;
public viewHolder(#NonNull View itemView) {
super(itemView);
bumpernumber=itemView.findViewById(R.id.bumpernumber);
description=itemView.findViewById(R.id.description);
nsn=itemView.findViewById(R.id.nsn);
serialnumber=itemView.findViewById(R.id.serialnumber);
date=itemView.findViewById(R.id.date);
more=itemView.findViewById(R.id.more);
}
}
public interface OnNoteItemClickListener{
void Onclick(noteModel model);
void OnEdit(noteModel model);
}
public void setOnNoteItemClickListener(OnNoteItemClickListener listener){
this.listener=listener;
}
}
in my database folder i have MySqliteHelper.java & TableSchema.java
MySqliteHelper.java
package com.example.mechanicsapp.database;
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 com.google.android.material.tabs.TabLayout;
import com.example.mechanicsapp.Model.noteModel;
import java.util.ArrayList;
import java.util.List;
public class MySqliteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="note.db";
private static final int VERSION=1;
public MySqliteHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String table1="create table "+TableSchema.note.TABLE_NAME+"("+TableSchema.note.ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+TableSchema.note.BUMPERNUMBER+" TEXT, "+TableSchema.note.DESCRIPTION+" TEXT,"+TableSchema.note.NSN+" TEXT,"+TableSchema.note.SERIALNUMBER+" TEXT, "+TableSchema.note.DATE+" TEXT );";
sqLiteDatabase.execSQL(table1);
}
public boolean saveNote(noteModel model){
SQLiteDatabase database=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(TableSchema.note.BUMPERNUMBER,model.getBumpernumber());
cv.put(TableSchema.note.DESCRIPTION,model.getDescription());
cv.put(TableSchema.note.NSN,model.getNsn());
cv.put(TableSchema.note.SERIALNUMBER,model.getSerialnumber());
cv.put(TableSchema.note.DATE,model.getDate());
long id= database.insert(TableSchema.note.TABLE_NAME,null,cv);
return id != -1;
}
public List<noteModel> getAllNotes(){
SQLiteDatabase database= this.getReadableDatabase();
String[] cols={TableSchema.note.ID,TableSchema.note.BUMPERNUMBER,TableSchema.note.DESCRIPTION,TableSchema.note.NSN,TableSchema.note.SERIALNUMBER,TableSchema.note.DATE};
Cursor cursor=database.query(TableSchema.note.TABLE_NAME,cols,null,null,null,null,TableSchema.note.ID+" DESC");
ArrayList<noteModel> list=new ArrayList<>();
while (cursor.moveToNext()){
noteModel model=new noteModel();
model.setId(cursor.getInt(cursor.getColumnIndexOrThrow(TableSchema.note.ID)));
model.setBumpernumber(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.BUMPERNUMBER)));
model.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.DESCRIPTION)));
model.setNsn(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.NSN)));
model.setSerialnumber(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.SERIALNUMBER)));
model.setDate(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.DATE)));
list.add(model);
}
cursor.close();
database.close();
return list;
}
public boolean delNoteById(String id){
SQLiteDatabase database=this.getWritableDatabase();
int d_id=database.delete(TableSchema.note.TABLE_NAME,TableSchema.note.ID+"=?",new String[]{id});
if (d_id==-1){
database.close();
return false;
}
database.close();
return true;
}
public boolean updateNoteById(noteModel model){
SQLiteDatabase database=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(TableSchema.note.BUMPERNUMBER,model.getBumpernumber());
values.put(TableSchema.note.DESCRIPTION,model.getDescription());
values.put(TableSchema.note.NSN,model.getNsn());
values.put(TableSchema.note.SERIALNUMBER,model.getSerialnumber());
values.put(TableSchema.note.DATE,model.getDate());
int u_id=database.update(TableSchema.note.TABLE_NAME,values,TableSchema.note.ID+"=?",new String[]{String.valueOf(model.getId())});
if (u_id==-1){
database.close();
return false;
}
database.close();
return true;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
if (i<i1){
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TableSchema.note.TABLE_NAME);
}
}
}
TableSchema.java
package com.example.mechanicsapp.database;
public class TableSchema {
public static class note{
public static final String TABLE_NAME="tbl_note";
public static final String ID="id";
public static final String BUMPERNUMBER="bumpernumber";
public static final String DESCRIPTION="description";
public static final String NSN="nsn";
public static final String SERIALNUMBER="serialnumber";
public static final String DATE="date";
}
}
in my Model folder i have noteModel.java
//noteModel.java
package com.example.mechanicsapp.Model;
public class noteModel {
private int id;
private String bumpernumber;
private String description;
private String nsn;
private String serialnumber;
private String date;
public noteModel() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBumpernumber() {
return bumpernumber;
}
public void setBumpernumber(String bumpernumber) {
this.bumpernumber = bumpernumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getNsn() {
return nsn;
}
public void setNsn(String nsn) {
this.nsn = nsn;
}
public String getSerialnumber() {
return serialnumber;
}
public void setSerialnumber(String serialnumber) {
this.serialnumber = serialnumber;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
fragment_equipment_tracker.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=".EquipmentTracker">
<LinearLayout
android:layout_centerInParent="true"
android:padding="10dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/bumpernumber"
android:hint="Bumper Number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/description"
android:hint="Enter description"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/nsn"
android:hint="Enter nsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/serialnumber"
android:hint="Enter serial number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/date"
android:hint="Enter date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnSave"
android:text="Save"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnDisplay"
android:text="Display"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
activity_equipment_tracker_allnotes.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EquipmentTrackerAllnotes">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
edit_note.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=".EquipmentTracker">
<LinearLayout
android:padding="10dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/bumpernumber"
android:hint="Bumper Number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/description"
android:hint="Enter description"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/nsn"
android:hint="Enter nsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/serialnumber"
android:hint="Enter serial number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/date"
android:hint="Enter date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnUpdate"
android:text="Update"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
//row_note.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"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_margin="10dp"
android:padding="10dp"
cardElevation="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/bumpernumber"
android:textSize="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/nsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/serialnumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<ImageView
android:id="#+id/more"
android:src="#drawable/baseline_more_vert_24"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
more_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/edit" android:title="edit"/>
<item android:id="#+id/delete" android:title="Delete"/>
</menu>
Related
I am trying to develop an application in android with the help of Geeks for Geeks tutorials. I am still learning how to develop android apps. It is a simple weather app where I need to display forecast in recycler view with the help of card view. The code is as shown from the video, but still the recycler view is not getting displayed. API url is also working. There is no error shown.
App Permissions - Location and Internet (Added in Manifest)
It was a request to please help me out with this issue.
Please do reply.
Main_Activity.java file is just a splash screen.
Main_Activity2.java
package com.androidp.wheatherapp;
import androidx.annotation.NonNull;
import androidx.appcompat.
app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private RelativeLayout rlayout;
private ProgressBar pbar;
private TextView cityNameiv;
private TextView temp;
private TextView condi;
private EditText editCity;
private ImageView IVsearch,ivicon,backIV;
private RecyclerView recyclerWeather;
private ArrayList<WeatherModal> weatherModalArrayList;
private weatherAdapter adapter;
private String cityName;
private LocationManager locationManager;
private int PERMISSION_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
rlayout = findViewById(R.id.rlayout);
pbar = findViewById(R.id.pbar);
cityNameiv = findViewById(R.id.cityName);
temp = findViewById(R.id.temp);
condi = findViewById(R.id.condi);
editCity = findViewById(R.id.editCity);
ivicon = findViewById(R.id.ivicon);
IVsearch = findViewById(R.id.IVsearch);
recyclerWeather = findViewById(R.id.recyclerWeather);
backIV = findViewById(R.id.backIV);
weatherModalArrayList = new ArrayList<>();
adapter = new weatherAdapter(this,weatherModalArrayList);
recyclerWeather.setAdapter(adapter);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity2.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_CODE);
}
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
cityName = getCityName(location.getLongitude(), location.getLatitude());
getweatherInfo(cityName);
IVsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city = editCity.getText().toString();
if(city.isEmpty()){
Toast.makeText(MainActivity2.this,"Please Enter City Name",Toast.LENGTH_SHORT).show();
}
else {
cityNameiv.setText(cityName);
getweatherInfo(city);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == PERMISSION_CODE){
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this,"Allow Permissions",Toast.LENGTH_SHORT).show();
finish();
}
}
}
private String getCityName(double longitude, double latitude){
String cityName = "Not Found";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = gcd.getFromLocation(latitude,longitude,10);
for (Address adr : addresses){
if(adr!= null){
String city = adr.getLocality();
if(city!= null && !city.equals("")){
cityName = city;
}
else {
Log.d("TAG","User City not found");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
private void getweatherInfo(String cityName){
String url="https://api.weatherapi.com/v1/forecast.json?key=deadad1688ef46f8929170126213010&q="+ cityName+"&days=1&aqi=no&alerts=no";
//cityNameiv.setText(cityName);
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity2.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pbar.setVisibility(View.GONE);
rlayout.setVisibility(View.VISIBLE);
//weatherModalArrayList.clear();
try {
String temperature = response.getJSONObject("current").getString("temp_c");
temp.setText(temperature + " °c");
int isDay = response.getJSONObject("current").getInt("is_day");
String condition = response.getJSONObject("current").getJSONObject("condition").getString("text");
String condiicon = response.getJSONObject("current").getJSONObject("condition").getString("icon");
Picasso.get().load("https:".concat(condiicon)).into(ivicon);
condi.setText(condition);
if(isDay==1){
Picasso.get().load("https://wallpaperaccess.com/full/929229.jpg").into(backIV);
}
else {
Picasso.get().load("https://wallpaperaccess.com/full/929229.jpg").into(backIV);
}
JSONObject forecastObj = response.getJSONObject("forecast");
JSONObject forecast0 = forecastObj.getJSONArray("forecastday").getJSONObject(0);
JSONArray hourarray = forecast0.getJSONArray("hour");
for(int i=0; i < hourarray.length();i++){
JSONObject hourobj = hourarray.getJSONObject(i);
String time = hourobj.getString("time");
String temp1 = hourobj.getString("temp_c");
String img = hourobj.getJSONObject("time").getString("icon");
String wind = hourobj.getString("wind_kph");
weatherModalArrayList.add(new WeatherModal(time,temp1,img,wind));
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,"Please enter valid city Name",Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
activity_main2.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=".MainActivity2">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pbar"
android:layout_centerInParent="true"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rlayout"
android:visibility="visible"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:id="#+id/backIV"
android:src="#color/black"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:gravity="center"
android:textColor="#color/white"
android:padding="20sp"
android:layout_marginTop="30dp"
android:textSize="18sp"
android:id="#+id/cityName"
android:text="City Name"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/idlin"
android:layout_below="#+id/cityName"
android:weightSum="5">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/editCity"
android:layout_margin="10sp"
android:layout_weight="4.5"
android:background="#color/white"
android:hint="Enter City"
android:padding="10dp"
app:hintTextColor="#color/purple_200"
/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:layout_margin="10dp"
android:tint="#color/white"
android:layout_gravity="center"
android:id="#+id/IVsearch"
android:src="#drawable/search"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/temp"
android:layout_margin="10dp"
android:gravity="center_horizontal"
android:padding="5dp"
android:textSize="70dp"
android:text="23"
android:textColor="#color/white"
android:layout_below="#id/idlin"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivicon"
android:layout_below="#id/temp"
android:src="#mipmap/ic_launcher"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/condi"
android:layout_margin="10dp"
android:gravity="center"
android:text="Condition"
android:textColor="#color/white"
android:textAlignment="center"
android:layout_below="#id/ivicon"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginBottom="10dp"
android:text="Today's Wheather Forecast"
android:layout_above="#id/recyclerWeather"
android:textColor="#color/white"
android:textStyle="bold"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerWeather"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</RelativeLayout>
</RelativeLayout>
weatherAdapter.java
package com.androidp.wheatherapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class weatherAdapter extends RecyclerView.Adapter<weatherAdapter.ViewHolder> {
private Context context;
private ArrayList<WeatherModal> weatherModalArrayList;
public weatherAdapter(Context context, ArrayList<WeatherModal> weatherModalArrayList) {
this.context = context;
this.weatherModalArrayList = weatherModalArrayList;
}
#NonNull
#Override
public weatherAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.weather_rv,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull weatherAdapter.ViewHolder holder, int position) {
WeatherModal modal = weatherModalArrayList.get(position);
holder.idTemperature.setText(modal.getTemperature() + "°c");
Picasso.get().load("https:".concat(modal.getIcon())).into(holder.idCondition);
holder.wind.setText(modal.getWindSpeed()+"km/hr");
SimpleDateFormat input = new SimpleDateFormat("yyyy-mm-dd hh:mm");
SimpleDateFormat output = new SimpleDateFormat("hh:min aa");
try {
Date t = input.parse(modal.getTime());
holder.idTime.setText(output.format(t));
}catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return weatherModalArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView idTemperature, idTime, wind;
private ImageView idCondition;
public ViewHolder(#NonNull View itemView) {
super(itemView);
idCondition = itemView.findViewById(R.id.idCondition);
idTemperature = itemView.findViewById(R.id.idTemperature);
wind = itemView.findViewById(R.id.idTextview);
idTime = itemView.findViewById(R.id.idTime);
}
}
}
WeatherModal.java
package com.androidp.wheatherapp;
public class WeatherModal {
private String Time;
private String Temperature;
private String icon;
private String windSpeed;
public WeatherModal(String time, String temperature, String icon, String windSpeed) {
Time = time;
Temperature = temperature;
this.icon = icon;
this.windSpeed = windSpeed;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getTemperature() {
return Temperature;
}
public void setTemperature(String temperature) {
Temperature = temperature;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getWindSpeed() {
return windSpeed;
}
public void setWindSpeed(String windSpeed) {
this.windSpeed = windSpeed;
}
}
weather_rv.xml - Card View
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="center"
app:cardElevation="6dp"
app:cardCornerRadius="10dp"
android:layout_margin="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/card_bag"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/idTime"
android:gravity="center"
android:padding="4dp"
android:text="TIME"
android:textColor="#color/black"
android:textAlignment="center"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/idTemperature"
android:gravity="center"
android:textSize="20sp"
android:text="20"
android:textAlignment="center"
android:layout_below="#+id/idTime"
android:textColor="#color/white"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#+id/idTemperature"
android:id="#+id/idCondition"
android:layout_centerHorizontal="true"
android:layout_margin="5dp"
android:padding="4dp"
android:src="#drawable/ic_launcher_foreground"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:layout_below="#id/idCondition"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/idTextview"
android:textColor="#color/white"
android:padding="3dp"
android:layout_margin="4dp"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
ScreenShot Of App
The recycler view is to be displayed below Today's Weather Forecast
I'm having an issue with my app when I inflate an recyclerview.
Inside the recyclerview, some cards are inflated and when it comes out to the screen, the toolbar disappears and the settings button can't be used.
Using the latest SDK and libraries versions.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/conteudoRSS"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
linha.xml -> here I get the cardview which I use to show the items on the recyclerview
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="#style/CardView.Light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/titulo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:textAppearance="#style/TextAppearance.AppCompat.Title"
android:textColor="#000000"
tools:text="Titulo Noticia"
app:layout_constraintEnd_toStartOf="#+id/imagem"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/dataPublicacao"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#8A000000"
tools:text="18 Setembro 2020"
app:layout_constraintEnd_toStartOf="#+id/imagem"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/titulo" />
<ImageView
android:id="#+id/imagem"
android:layout_width="140dp"
android:layout_height="140dp"
android:layout_margin="12dp"
tools:background="#color/colorAccent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/url"
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="invisible"
tools:ignore="MissingConstraints"
app:layout_constraintTop_toBottomOf="#+id/dataPublicacao" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
MainActivity.java
package br.ufpe.cin.android.rss;
import androidx.appcompat.app.AppCompatActivity;
package br.ufpe.cin.android.rss;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.prof.rssparser.Article;
import com.prof.rssparser.Channel;
import com.prof.rssparser.OnTaskCompleted;
import com.prof.rssparser.Parser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private String urlFeed;
private Toolbar mTopToolbar;
RecyclerView conteudoRSS;
List<Article> noticias;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudoRSS = findViewById(R.id.conteudoRSS);
mTopToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mTopToolbar);
SharedPreferences preferences = getSharedPreferences
("user_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("feed1", getString(R.string.feed1));
editor.putString("feed2", getString(R.string.feed2));
editor.putString("feed3", getString(R.string.feed3));
editor.apply();
if(preferences.contains("rssfeed")){
urlFeed = preferences.getString("rssfeed", getString(R.string.feed_padrao));
} else {
editor.putString("rssfeed", getString(R.string.feed_padrao));
editor.apply();
urlFeed = preferences.getString("rssfeed", getString(R.string.feed_padrao));
}
conteudoRSS = new RecyclerView(this);
conteudoRSS.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
startActivity(new Intent(
this, PreferenciasActivity.class));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStart() {
super.onStart();
Parser p = new Parser.Builder().build();
p.onFinish(
new OnTaskCompleted() {
#Override
public void onTaskCompleted(Channel channel) {
noticias = channel.getArticles();
runOnUiThread(
() -> {
RssAdapter adapter = new RssAdapter(
getApplicationContext(),
noticias
);
conteudoRSS.setAdapter(adapter);
setContentView(conteudoRSS);
}
);
}
#Override
public void onError(Exception e) {
Log.e("RSS_APP",e.getMessage());
}
}
);
p.execute(urlFeed);
}
protected void onResume() {
super.onResume();
}
private String getRssFeed(String feed) throws IOException {
InputStream in = null;
String rssFeed;
try {
URL url = new URL(feed);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
byte[] response = out.toByteArray();
rssFeed = new String(response, StandardCharsets.UTF_8);
} finally {
if (in != null) {
in.close();
}
}
return rssFeed;
}
}
conteudoRSS = new RecyclerView(this);
conteudoRSS.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
startActivity(new Intent(
this, PreferenciasActivity.class));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStart() {
super.onStart();
Parser p = new Parser.Builder().build();
p.onFinish(
new OnTaskCompleted() {
#Override
public void onTaskCompleted(Channel channel) {
noticias = channel.getArticles();
runOnUiThread(
() -> {
RssAdapter adapter = new RssAdapter(
getApplicationContext(),
noticias
);
conteudoRSS.setAdapter(adapter);
setContentView(conteudoRSS);
}
);
}
#Override
public void onError(Exception e) {
Log.e("RSS_APP",e.getMessage());
}
}
);
p.execute(urlFeed);
}
protected void onResume() {
super.onResume();
}
private String getRssFeed(String feed) throws IOException {
InputStream in = null;
String rssFeed;
try {
URL url = new URL(feed);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
byte[] response = out.toByteArray();
rssFeed = new String(response, StandardCharsets.UTF_8);
} finally {
if (in != null) {
in.close();
}
}
return rssFeed;
}
}
ItemRssViewHolder.java
package br.ufpe.cin.android.rss;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
public class ItemRssViewHolder extends RecyclerView.ViewHolder {
TextView titulo = null;
ImageView image = null;
TextView data = null;
TextView url = null;
public ItemRssViewHolder(View itemCard) {
super(itemCard);
this.titulo = itemCard.findViewById(R.id.titulo);
this.image = itemCard.findViewById(R.id.imagem);
this.data = itemCard.findViewById(R.id.dataPublicacao);
this.url = itemCard.findViewById(R.id.url);
itemCard.setOnClickListener(
v -> {
String uri = url.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(uri));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
itemCard.getContext().startActivity(intent);
}
);
}
}
RssAdapter.java
package br.ufpe.cin.android.rss;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.prof.rssparser.Article;
import com.squareup.picasso.Picasso;
import java.util.List;
import static br.ufpe.cin.android.rss.R.layout.linha;
public class RssAdapter extends RecyclerView.Adapter <ItemRssViewHolder> {
List<Article> noticias;
Context context;
public RssAdapter(Context c, List<Article> noticias) {
this.noticias = noticias;
this.context = c;
}
public int getCount() {
return noticias.size();
}
public Object getItem(int i) {
return noticias.get(i);
}
#NonNull
#Override
public ItemRssViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.linha, parent, false);
ItemRssViewHolder viewHolder = new ItemRssViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ItemRssViewHolder viewHolder, int i) {
Article noticia = noticias.get(i);
viewHolder.titulo.setText(noticia.getTitle());
viewHolder.data.setText("Publicado em: " + noticia.getPubDate().substring(0, 22));
viewHolder.url.setText(noticia.getLink());
String url = noticias.get(i).getImage();
Picasso.with(context)
.load(url)
.into(viewHolder.image);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getItemCount() {
return noticias.size();
}
}
Because you align the top of Recyclerview to the top of parent (ConstraintLayout) so it overs the toolbar.
Replace app:layout_constraintTop_toTopOf="parent" with app:layout_constraintTop_toBottomOf="#id/toolbar" to align the top of Recyclerview to the bottom of Toolbar
Add these attrs to your Toolbar:
app:layout_constraintBottom_toTopOf="#id/conteudoRSS"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
<?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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="#id/conteudoRSS"
tools:ignore="MissingConstraints">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/conteudoRSS"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/toolbar"/> <!-- replace app:layout_constraintTop_toTopOf="parent" -->
</androidx.constraintlayout.widget.ConstraintLayout>
LinearLayout is also good, it's simpler than ConstraintLayout in this case
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/conteudoRSS"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
Try this
<?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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#id/conteudoRSS"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/toolbar"
app:layout_constraintStart_toStartOf="parent">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/conteudoRSS"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/toolbar" /><!--TODO:Edit-->
</androidx.constraintlayout.widget.ConstraintLayout>
If this does not work, try adding android:layout_marginTop="?attr/actionBarSize" to RecyclerView.
Hope this helps. Feel free to ask for clarifications...
Issue fixed with the help of Vishnu, who's answered this question.
It seems the problem was that I was creating a new recycleview on the main activity instead of using the recycleview defined by the layout xml file.
To fix that, it was only necessary to remove two lines from the main activity:
conteudoRSS = new RecyclerView(this);
setContentView(conteudoRSS);
And maintain only the first definition of the recycleview, as follows:
RecyclerView conteudoRSS;
conteudoRSS = findViewById(R.id.conteudoRSS);
my recyclerview show one data but i receive multiple data in logcat in the form of json
Here is main file
Stitle.java
package com.desktop.app;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Stitle extends AppCompatActivity {
EditText searchtitle;
private RequestQueue requestQueue ;
private List<list> productList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerView.Adapter listAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stitle);
searchtitle = findViewById(R.id.searchtitle);
searchtitle.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
foji();
setContentView(R.layout.activity_smain);
listAdapter = new listAdapter(Stitle.this,productList);
recyclerView = (RecyclerView) findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(Stitle.this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(listAdapter);
return true;
}
return false;
}
});
}
public void foji(){
RequestQueue requestQueue=Volley.newRequestQueue(this);
Uri.Builder builder=new Uri.Builder();
builder.scheme("http")
.authority("192.168.0.136")
.appendPath("fyp")
.appendPath("stitle.php")
.appendQueryParameter("Title",searchtitle.getText().toString());
StringRequest stringRequest=new StringRequest(Request.Method.POST, builder.build().toString(), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("Info",response.toString());
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("search");
for(int i=0;i<jsonArray.length();i++){
JSONObject product=jsonArray.getJSONObject(i);
boolean add = productList.add(new list(
product.getLong("isbn"),
product.getString("title"),
product.getString("authors"),
product.getInt("accession"),
product.getString("publisher"),
product.getInt("pubyear"),
product.getInt("pages"),
product.getInt("rak"),
product.getInt("hr"),
product.getInt("vr"),
product.getLong("barcode")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Stitle.this, "Foji Error", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
}
}
Here is file for setter and getter
list.java
package com.desktop.app;
import java.io.Serializable;
public class list implements Serializable {
private long isbn;
private String title;
private String authors;
private int accession;
private String publisher;
private int pubyear;
private int pages;
private int rak;
private int hr;
private int vr;
private long barcode;
public list(long isbn, String title, String authors, int accession, String publisher, int pubyear, int pages, int rak, int hr, int vr, long barcode) {
this.isbn = isbn;
this.title = title;
this.authors = authors;
this.accession = accession;
this.publisher = publisher;
this.pubyear = pubyear;
this.pages = pages;
this.rak = rak;
this.hr = hr;
this.vr = vr;
this.barcode = barcode;
}
public long getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public String getAuthors() {
return authors;
}
public int getAccession() {
return accession;
}
public String getPublisher() {
return publisher;
}
public int getPubyear(){
return pubyear;
}
public int getPages(){
return pages;
}
public int getRak(){
return rak;
}
public int getHr(){
return hr;
}
public int getVr(){
return vr;
}
public long getBarcode() {
return barcode;
}
public void setIsbn(long isbn) {
this.isbn = isbn;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public void setAccession(int accession) {
this.accession = accession;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public void setPubyear(int pubyear) {
this.pubyear = pubyear;
}
public void setPages(int pages) {
this.pages = pages;
}
public void setRak(int rak) {
this.rak = rak;
}
public void setHr(int hr) {
this.hr = hr;
}
public void setVr(int vr) {
this.vr = vr;
}
public void setBarcode(long barcode) {
this.barcode = barcode;
}
}
Here is file of lisAdapter
listAdapter.java
package com.desktop.app;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
public class listAdapter extends RecyclerView.Adapter<listAdapter.ProductViewHolder> {
RequestOptions options ;
private Context mCtx;
private List<list> pdata;
listAdapter(Context mCtx, List productList) {
this.mCtx = mCtx;
this.pdata = productList;
}
#Override
public ProductViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View view ;
LayoutInflater inflater = LayoutInflater.from(mCtx);
view = inflater.inflate(R.layout.slist,parent,false);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder( ProductViewHolder holder, final int position) {
list product = pdata.get(position);
holder.textviewisbn.setText(String.valueOf(product.getIsbn()));
holder.textviewtitle.setText(product.getTitle());
holder.textviewauthors.setText(product.getAuthors());
holder.textviewacc.setText(String.valueOf(product.getAccession()));
holder.textviewpublisher.setText(product.getPublisher());
holder.textviewpubyear.setText(String.valueOf(product.getPubyear()));
}
#Override
public int getItemCount() {
return pdata.size();
}
public static class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textviewisbn, textviewtitle, textviewauthors, textviewacc, textviewpublisher, textviewpubyear;
public ProductViewHolder(View itemView) {
super(itemView);
textviewisbn = itemView.findViewById(R.id.textviewisbn);
textviewtitle = itemView.findViewById(R.id.textviewtitle);
textviewauthors = itemView.findViewById(R.id.textviewauthors);
textviewacc = itemView.findViewById(R.id.textviewacc);
textviewpublisher = itemView.findViewById(R.id.textviewpublisher);
textviewpubyear = itemView.findViewById(R.id.textviewpubyear);
}
}
}
slist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/textviewisbn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_above="#id/textviewtitle"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textviewtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textviewauthors"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewtitle"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small" />
<TextView
android:id="#+id/textviewacc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewauthors"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/textviewpublisher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewacc"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/textviewpubyear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewpublisher"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
recylerview xml file
activity_smain.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.desktop.app.listactivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="-51dp" >
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Recyclerview show one data but i receive multiple data in logcat in the form of json
I/Info: {"status":true,"search":[{"isbn":195472462,"title":"Oxford Practice Grammer","authors":"john Eastwood","accession":1,"publisher":"Ameena Saiyid Oxford University","pubyear":2014,"pages":432,"rak":1,"hr":1,"vr":1,"barcode":195472462},{"isbn":9694946719,"title":"High School English Grammer ","authors":"Wren, martin","accession":4,"publisher":"Paramount Publishing","pubyear":2010,"pages":418,"rak":1,"hr":1,"vr":4,"barcode":9694946719}]}
this data recieve as json but only one record show in list image show's that only one record on list
You can see the data on scroll because you have set the list item height to
match_parent.. you just need to set it to wrap_content
slist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/textviewisbn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_above="#id/textviewtitle"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textviewtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textviewauthors"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewtitle"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small" />
<TextView
android:id="#+id/textviewacc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewauthors"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/textviewpublisher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewacc"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/textviewpubyear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewpublisher"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
I'm a beginner with Android and struggling with the implementation of a RecyclerView. Was working through a tutorial and changing the values to what I need. But when I start, the view stays empty. As far as I was planning, it was supposed to show 20 times the same item for the moment.
ExerciseList.java (Start Activity):
package com.example.erik.orlandoapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class ExerciseList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.title_activity_exercise_list));
setContentView(R.layout.activity_exercise_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
ExerciseBlock.java:
package com.example.erik.orlandoapp;
import java.util.ArrayList;
import java.util.List;
public class ExerciseBlock {
private String title;
private int difficulty;
private int exerciseId;
private static int lastId = 0;
public ExerciseBlock(String title, int difficulty, int exerciseId) {
this.title = title;
this.difficulty = difficulty;
this.exerciseId = exerciseId;
}
public String getTitle() {
return title;
}
public int getDifficulty() {
return difficulty;
}
public int getExerciseId() {
return exerciseId;
}
public static ArrayList<ExerciseBlock> createContactsList(int numContacts) {
ArrayList<ExerciseBlock> exerciseBlocks = new ArrayList<ExerciseBlock>();
for (int i = 1; i <= numContacts; i++) {
exerciseBlocks.add(new ExerciseBlock("Title",1,1));
}
return exerciseBlocks;
}
}
ExerciseBlockAdapter.java:
package com.example.erik.orlandoapp;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class ExerciseBlockAdapter extends RecyclerView.Adapter<ExerciseBlockAdapter.ViewHolder> {
private List<ExerciseBlock> exList;
private Context mContext;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.exercise_item, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
ExerciseBlock exBlock = exList.get(position);
TextView textView = viewHolder.getTxtDiff();
textView.setText(exBlock.getDifficulty());
textView = viewHolder.getTxtExercise();
textView.setText(exBlock.getExerciseId());
}
#Override
public int getItemCount() {
return exList.size();
}
public ExerciseBlockAdapter(Context context, List<ExerciseBlock> exList) {
this.exList = exList;
this.mContext = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView txtExercise;
private TextView txtDiff;
public TextView getTxtExercise() {
return this.txtExercise;
}
public TextView getTxtDiff() {
return this.txtDiff;
}
public ViewHolder(View itemView) {
super(itemView);
txtDiff = (TextView) itemView.findViewById(R.id.txtExDiff);
txtExercise = (TextView) itemView.findViewById(R.id.txtExName);
}
}
}
UserListActivity:
package com.example.erik.orlandoapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class UserListActivity extends AppCompatActivity {
ArrayList<ExerciseBlock> exerciseBlocks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.exerciseList);
exerciseBlocks = ExerciseBlock.createContactsList(20);
ExerciseBlockAdapter adapter = new ExerciseBlockAdapter(this, exerciseBlocks);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
}
}
activity_exercise_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.erik.orlandoapp.ExerciseList">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/exerciseList"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
exercise_item.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="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:weightSum="1">
<TextView
android:id="#+id/txtExName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Whatever" />
<TextView
android:id="#+id/txtExDiff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorDifEasy"
android:paddingBottom="6dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="6dp"
android:text="Leicht"
android:textSize="10sp" />
</LinearLayout>
Thanks a lot!
I don't see UserListActivity calling setContentView()
Either put this code inside ExersiceList Activity
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.exerciseList);
exerciseBlocks = ExerciseBlock.createContactsList(20);
ExerciseBlockAdapter adapter = new ExerciseBlockAdapter(this, exerciseBlocks);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
or call setContentView(R.layout.activity_exercise_layout) on Your UserListActivity
I'm new in android and I just try to use this code and show the save data on database in listView. but when i press the button say unfortunately has stopped. please help me.
MainActivity Class
package com.example.employeedetailsnew;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
public class MainActivity extends Activity{
private EditText nme = null;
private EditText num = null;
private EmployeeDatabase empObj;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nme = (EditText) findViewById(R.id.name);
num = (EditText) findViewById(R.id.ageemp);
Button btnShowData = (Button) findViewById(R.id.button2);
btnShowData.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
onSaveClick();
}
});
}
public void onButtonClicked(View view) {
if (nme.length()!=0 && num.length()!=0){
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
String varName = nme.getText().toString();
String varAge = num.getText().toString();
empObj = new EmployeeDatabase(getApplicationContext());
empObj.insert(varName,varAge,strDate);
AlertDialog alertDialog = null;
alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle(getResources().getString(R.string.Message));
alertDialog.setMessage(getResources().getString(R.string.You_have_been_Registered));
alertDialog.setCancelable(true);
alertDialog.show();
nme.setText("");
num.setText("");
}else{
Toast toast = Toast.makeText(getApplicationContext(), getResources().getString(R.string.Empty_Item),
Toast.LENGTH_SHORT);
toast.show();
}
}
public void onSaveClick(){
Intent intent = new Intent(this, ShowData.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Detail Class
package com.example.employeedetailsnew;
public class DetailClass {
private String name;
private String age;
private String time;
public String getName() {
return name;
}
public String getAge() {
return age;
}
public String getTime() {
return time;
}
}
MyAdaptor Class
package com.example.employeedetailsnew;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MyAdapter extends CursorAdapter {
public MyAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int index, View view, ViewGroup parent) {
if (view == null)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.shows_view, parent, false);
}
ArrayList times = null;
DetailClass empDtl = (DetailClass) times.get(index);
TextView nameTextView = (TextView) view.findViewById(R.id.name1);
nameTextView.setText(empDtl.getName());
TextView ageTextView = (TextView) view.findViewById(R.id.age2);
ageTextView.setText(empDtl.getAge());
TextView timeTextView = (TextView) view.findViewById(R.id.time3);
timeTextView.setText((CharSequence) empDtl.getTime());
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView nameTextView = (TextView) view.findViewById(R.id.name1);
nameTextView.setText(cursor.getString(cursor.getColumnIndex("name")));
TextView ageTextView = (TextView) view.findViewById(R.id.name1);
ageTextView.setText(cursor.getString(cursor.getColumnIndex("age")));
TextView timeTextView = (TextView) view.findViewById(R.id.name1);
timeTextView.setText(cursor.getString(cursor.getColumnIndex("time")));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from (parent.getContext());
View view = inflater.inflate(R.layout.shows_list, parent, false);
return view;
}
}
MyDataBase Class
package com.example.employeedetailsnew;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
class EmployeeDatabase extends SQLiteOpenHelper{
EmployeeDatabase (Context context) {
super(context, "empdb.db", null,3);
}
#Override
public void onCreate(SQLiteDatabase database)
{
database.execSQL("create table employee" + "(name TEXT , age TEXT, time TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
{
database.execSQL("DROP TABLE IF EXISTS EMPLOYEEDETAILNEW");
onCreate(database);
}
public Cursor getDetails()
{
SQLiteDatabase db = getReadableDatabase();
return db.rawQuery("select rowid _id,name, age,time from employeedetailnew", null);
}
public void insert(String name, String age, String time)
{
long rowId = 0;
try{
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("age", age);
contentValues.put("time", time);
rowId = db.insert("employeedetailnew", null, contentValues);
}catch(Exception e){
e.printStackTrace();
}
finally{
System.out.println("The rowId is "+rowId);
System.out.println("Name is "+name);
System.out.println("Age is "+age);
System.out.println("Time is "+time);
}
}
public boolean deleteTitle(String name)
{
SQLiteDatabase db = getWritableDatabase();
return db.delete("employeedetailnew", name + "=" + name, null) > 0;
}
}
ShowData Class
package com.example.employeedetailsnew;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
public class ShowData extends ListActivity
{
private EmployeeDatabase databaseHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shows_list);
EmployeeDatabase empClick = new EmployeeDatabase(getApplicationContext());
Cursor cursor = empClick.getDetails();
if (cursor.moveToFirst())
{
do
{
String name = cursor.getString(1);
String notes = cursor.getString(2);
String time = cursor.getString(3);
} while (cursor.moveToNext());
}
if (!cursor.isClosed())
{
cursor.close();
}
}
}
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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.employeedetailsnew.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/empname"
android:layout_below="#+id/empname"
android:layout_marginTop="19dp"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/sub"
android:layout_below="#+id/sub"
android:layout_marginTop="24dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1" />
<TextView
android:id="#+id/empname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="46dp"
android:layout_marginTop="27dp"
android:text="#string/name" />
<TextView
android:id="#+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name"
android:layout_below="#+id/name"
android:layout_marginTop="16dp"
android:text="#string/age" />
<EditText
android:id="#+id/ageemp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/age"
android:layout_below="#+id/age"
android:ems="10"
android:inputType="numberSigned" />
<Button
android:id="#+id/sub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button3"
android:layout_centerVertical="true"
android:onClick="onButtonClicked"
android:text="#string/sub" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="#string/show_data" />
</RelativeLayout>
shows_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
shows_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/name1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/age2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/time3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
and that's my logcat
08-16 11:52:08.427 28242-28242/com.example.employeedetailsnew E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.employeedetailsnew/com.example.employeedetailsnew.ShowData}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
at android.app.Activity.startActivityForResult(Activity.java:3390)
at android.app.Activity.startActivityForResult(Activity.java:3351)
at android.app.Activity.startActivity(Activity.java:3587)
at android.app.Activity.startActivity(Activity.java:3555)
at com.example.employeedetailsnew.MainActivity.onSaveClick(MainActivity.java:60)
at com.example.employeedetailsnew.MainActivity$1.onClick(MainActivity.java:30)
at android.view.View.performClick(View.java:4421)
at android.view.View$PerformClick.run(View.java:17903)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
add ShowData Activity in manifest.xml
<activity
android:name=".ShowDatata"/>