-1

I am making a notes app, when i click on any item in Recyclerview, i want to start a new activity and pass some String, i have referred many links even from stackoverflow and i tried them, still not working. Can you please help me, since i am just beginner in android.

This is my NotesAdapter

package org.terna.notes_aap;

/**
 * Created by Sohail on 8/23/2017.
 */

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;    
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.chauthai.swipereveallayout.ViewBinderHelper;    
import java.util.ArrayList;
import java.util.List;    
import static android.R.attr.name;

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyViewHolder> {

    private List<Note> noteList;
    private Context context;
    private ItemClickListener clickListener;
    private LayoutInflater mInflater;
    int i;
    private final ViewBinderHelper viewBinderHelper = new ViewBinderHelper();

    public void setClickListener(ItemClickListener itemClickListener) {
        this.clickListener = itemClickListener;
    }

    public NotesAdapter(List<Note> noteList, Context context) {
        this.noteList = noteList;
        this.context = context;
        mInflater = LayoutInflater.from(context);
        viewBinderHelper.setOpenOnlyOne(true);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_list_row, parent, false);
        return new MyViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {

        Note note = noteList.get(position); 
        holder.tid.setText(""+note.getId());
        holder.title.setText(note.getTitle());
        holder.description.setText(note.getDescription());
        holder.date.setText(note.getDate());
        holder.month.setText(note.getMonth());
        holder.year.setText(note.getYear());

            if (noteList != null && 0 <= position && position < noteList.size()) {
            final String data = noteList.get(position).toString();

              holder.bind(data);
        } 
    }  

    @Override
    public int getItemCount() {
        if (noteList == null)
            return 0;
        return noteList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private SwipeRevealLayout swipeLayout;
        private View deleteLayout;   
        public TextView tid, title, description,month, date, year;

        // this relativelayout is my row in recyclerview were i want the on click event.    
        public RelativeLayout relativeLayout;    
        Button button1;

        PersonDB db1=new PersonDB(context,"persondb2.db",null,1);
        ArrayList<PersonModel> persons = db1.getAllPersons();
        String id1;

        // i have created all objects here.
        public MyViewHolder(View view) {
            super(view);
            swipeLayout = (SwipeRevealLayout) itemView.findViewById(R.id.swipe_layout);
            deleteLayout = itemView.findViewById(R.id.delete_layout);

            tid = (TextView) view.findViewById(R.id.id);
            title = (TextView) view.findViewById(R.id.title);
            description = (TextView) view.findViewById(R.id.description);
            month = (TextView) view.findViewById(R.id.month);
            date = (TextView) view.findViewById(R.id.date);
            year = (TextView) view.findViewById(R.id.year);

            relativeLayout = (RelativeLayout) view.findViewById(R.id.list_row);
            button1 =(Button)view.findViewById(R.id.button1);

            relativeLayout.setOnClickListener(this);                
        }

        // this is for deletion of items in recycler view, its working fine.
        public void bind(String data) {
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                     i = Integer.parseInt(tid.getText().toString());    
                    db1.deletePerson(i);    
                    Toast.makeText(context, "DELETED id = "+tid.getText(), Toast.LENGTH_SHORT).show();    
                    noteList.remove(getAdapterPosition());
                    notifyItemRemoved(getAdapterPosition());
                }
            });
        }


        // I am passing the 'i' parameter because i want the id of the item which is clicked, so that i can perform update, delete note operation.

        // Is there any Other way to do it

        @Override
        public void onClick(View view) {

            i = Integer.parseInt(tid.getText().toString());
            if (clickListener != null) clickListener.onClick(view, getAdapterPosition(),i); // call the onClick in the OnItemClickListener
        }
    }

    public int getdata(){
        int s = i;
        return s;
    } 
}

This is the Itemclick listener interface I used to implement onClick

import android.view.View;

/**
 * Created by Sohail on 9/6/2017.
 */

public interface ItemClickListener {
    void onClick(View view, int position, int i);
}

This is my ListActivity

    package org.terna.notes_aap;

import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class ListActivity extends AppCompatActivity implements ItemClickListener{

    int c;
    int get;
    Note note;

    PersonDB db1=new PersonDB(this,"persondb2.db",null,1);

    private List<Note>noteList = new ArrayList<>();
    private RecyclerView recyclerView, listrow;
    private NotesAdapter notesAdapter;
    ImageButton addNote,appIcon;
    Button delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);

        notesAdapter = new NotesAdapter(noteList,this);
        RecyclerView.LayoutManager nLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(nLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(notesAdapter);
        notesAdapter.setClickListener(this);

        final Intent intent1 = new Intent(this,Add_Update_Activity.class);
        addNote = (ImageButton)(findViewById(R.id.addNote));
        appIcon = (ImageButton)(findViewById(R.id.appIcon));

        addNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                intent1.putExtra("check",1);
                startActivity(intent1);
            }
        });
        appIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

       /* db1.insertIntoPerson("Sudhanshu's song","Rock","2017");
        db1.insertIntoPerson("Akshay's song","Pop","2007");*/

        prepareNoteData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        ArrayList<PersonModel> persons = db1.getAllPersons();

        for(int i=persons.size()-1;i>=0;i--)
        {
            PersonModel person = persons.get(i);

            String title = person.title;
            int id = person.id;
            String description = person.description;
            String month = person.month;
            String date = person.date;
            String year = person.year;

            note = new Note(id,title,description,month,date,year);
            noteList.add(note);
        }
        notesAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onStop() {
        super.onStop();

        ArrayList<PersonModel> persons = db1.getAllPersons();

        c = persons.size();
        if(c !=0 ){
            for(int j=persons.size()-1;j>=0;j--){              
                noteList.removeAll(persons);
            }
        }
        noteList.clear();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    public void passdata(){    
        NotesAdapter n = null;

       int get = n.getdata();
        Toast.makeText(this, "get = "+get, Toast.LENGTH_SHORT).show();

    }

    private void prepareNoteData() {

        Toast.makeText(this, "i am in preparenote", Toast.LENGTH_SHORT).show();

        ArrayList<PersonModel> persons = db1.getAllPersons();
        for(int i=persons.size()-1;i>=0;i--)
        {
            PersonModel person = persons.get(i);
            String title = person.title;
            int id = person.id;
            String description = person.description;
            String month = person.month;
            String date = person.date;
            String year = person.year;

            Log.e("DB","Initialised");

            note = new Note(id,title,description,month,date,year);
            noteList.add(note);

        }
        notesAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view, int position, int i) {

        int p = i;    
        Toast.makeText(this, i+" is clicked", Toast.LENGTH_SHORT).show();
        Intent intent2 = new Intent(this,Add_Update_Activity.class);    
        startActivity(intent2);
    }
}

This is my Add_Update_Activity

    package org.terna.notes_aap;

import android.icu.text.DateFormat;
import android.icu.text.SimpleDateFormat;
import android.icu.util.Calendar;
import android.icu.util.TimeZone;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; 
import java.util.ArrayList;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

@RequiresApi(api = Build.VERSION_CODES.N)
public class Add_Update_Activity extends AppCompatActivity {

    EditText title1, description1;
    TextView label,month1,date1,year1;

    String title,description,month,date,year;
    int check;

    PersonDB db1=new PersonDB(this,"persondb2.db",null,1);

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add__update_);

        title1 = (EditText)(findViewById(R.id.title1));
        description1 = (EditText)(findViewById(R.id.description1));
        label = (TextView) (findViewById(R.id.label));
        month1 = (TextView) (findViewById(R.id.month));
        date1 = (TextView) (findViewById(R.id.date));
        year1 = (TextView) (findViewById(R.id.year));

        check = getIntent().getIntExtra("check",0);

        /*if(check == 1)
        {
            // Code for Creating new Note

            *//*Formatter mon = new Formatter();
            Calendar cal = Calendar.getInstance();
            mon = new Formatter();
            mon.format("%tb",cal);

            Calendar calendar = Calendar.getInstance();
            int y = calendar.get(Calendar.YEAR);

            year = String.valueOf(y);
            date = new SimpleDateFormat("EE", Locale.ENGLISH).format(cal.getTime());
            month = mon.toString();

            month = new SimpleDateFormat("MMM").format(new Date());
            date = new SimpleDateFormat("dd").format(new Date());
            year = new SimpleDateFormat("yyyy").format(new Date());
        }
        else
        {
            //  Code for Updating a Note
        }
        */
        month = new SimpleDateFormat("MMM").format(new Date());
        date = new SimpleDateFormat("dd").format(new Date());
        year = new SimpleDateFormat("yyyy").format(new Date());

        month1.setText(month);
        date1.setText(date);
        year1.setText(year);

        Toast.makeText(this, "month"+month+"  date"+date+"  year"+year, Toast.LENGTH_SHORT).show();    

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Toast.makeText(this, "add activity restarted", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();

        Toast.makeText(this, "add activity resumed", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        title = title1.getText().toString();
        description = description1.getText().toString();

        if(title.equals(""))
        {
            if(description.equals(""))
            {

            }
            else
            {
                Toast.makeText(this, "desc inserted", Toast.LENGTH_SHORT).show();
                db1.insertIntoPerson(title, description,month, date, year);

                onBackPressed();
            }
        }
        else
        {
            Toast.makeText(this, "title inserted", Toast.LENGTH_SHORT).show();
            db1.insertIntoPerson(title, description,month, date, year);
            onBackPressed();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

This is my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.terna.notes_aap">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SplashActivity" />
        <activity
            android:name=".ListActivity"
            android:label="@string/title_activity_list"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Add_Update_Activity"
            android:label="@string/title_activity_add__update_"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Edit_Update_Activity"
            android:label="@string/title_activity_edit__update_"
            android:theme="@style/AppTheme.NoActionBar"></activity>
    </application>

</manifest>

This all showed in my log

09-06 06:05:14.596 6726-6726/? E/FirebaseInstanceId: Failed to resolve target intent service, skipping classname enforcement
09-06 06:05:14.598 6726-6726/? E/FirebaseInstanceId: Error while delivering the message: ServiceIntent not found.
09-06 06:16:46.851 6726-6726/? E/FirebaseInstanceId: Failed to resolve target intent service, skipping classname enforcement
09-06 06:16:46.854 6726-6726/? E/FirebaseInstanceId: Error while delivering the message: ServiceIntent not found.

1 Answers1

0

You already passed the context to the adapter using the constructor:

public NotesAdapter(List<Note> noteList, Context context) {
    this.noteList = noteList;
    this.context = context;
    mInflater = LayoutInflater.from(context);
    viewBinderHelper.setOpenOnlyOne(true);
}

So in the onClickListener you can just use that one, no need to call for a context again, like this:

holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent i=new Intent(context1,Add_Update_Activity.class);

        Toast.makeText(context1, "i am clicked", Toast.LENGTH_SHORT).show();

        // When I comment it, my app works fine, I think something is missing here.
        context.startActivity(i);

    }
});

Though the way you are using it should not be causing a problem but there is just no need for doing the same thing twice.

SOLUTION:

In your Add_Update_Activity instead of

check = getIntent().getExtras().getInt("check");

use

check = getIntent().getIntExtra("check", 0);

Because when you don't send any extras getExtras method in the adapter will return null.

Marta
  • 11
  • 5
  • yes you are right, i did use only 1 context at start but still my app was crashing, so just to try out i created another. but same issue. can you please help – Sohail K. Shaikh Sep 05 '17 at 23:33
  • Well the first thing that comes to mind, have you properly set the Add_Update_Activity in the Manifest file? – Marta Sep 05 '17 at 23:35
  • yes Add_Update_Activity is there in manifest file, i have updated the code in my question. – Sohail K. Shaikh Sep 05 '17 at 23:44
  • That maybe the app crashes onCreate() on the Add_Update_Activity and not the context.startActivity(i) line. Have you considered this? – Marta Sep 05 '17 at 23:52
  • yes i also checked that, in my list activity(Activity were my recyclerview is present) i am calling the Add_Update_Activity successfully without any error.i am doing this on a button click which is present outside the recyclerview, i am updating that code in question. – Sohail K. Shaikh Sep 05 '17 at 23:55
  • Are you handling the case in the Add_Update_Activity if you don't pass this extra, intent1.putExtra("check",1)? Not passing it, and trying to use it could cause an NullPointerException. – Marta Sep 06 '17 at 00:12
  • yes i am using that putExtra("check",1) in my Add_Update_Activity, i am storing it in a variable in Add_Update_Activity, should i show the Add_Update_Activity code as well – Sohail K. Shaikh Sep 06 '17 at 00:24
  • the code in my Add_Update_Activity is actually incomplete (Logical part) but it has no errors – Sohail K. Shaikh Sep 06 '17 at 00:25
  • Well you are actually passing a integer as extra and the getIntExtra has an default value argument so this also isn't the issue. So yes, I guess we are only left with the option for you to show the Add_Update_Activity code because I'm out of ideas. It really doesn't help that you can't provide us with the error log. – Marta Sep 06 '17 at 00:31
  • sorry about that, but can you tell me how can i get log info, because my log is empty it dosent show anything maybe due to crash, i am uploading my Add_Update_Activity code – Sohail K. Shaikh Sep 06 '17 at 00:35
  • Well don't know what to suggest about this, maybe see if some of this help.. https://stackoverflow.com/questions/17432358/android-studio-logcat-nothing-to-show or https://stackoverflow.com/questions/28815356/android-studio-logcat-not-working – Marta Sep 06 '17 at 00:40
  • i think the problem somewhere lies in my NotesAdapter can you please check – Sohail K. Shaikh Sep 06 '17 at 00:44
  • In your Add_Update_Activity instead of check = getIntent().getExtras().getInt("check"); try using check = getIntent(). getIntExtra ("check", 0); Because when you don't send any extras getExtras() will return null. – Marta Sep 06 '17 at 09:04
  • Thank you so much, I did change to getIntExtra ("check", 0); in my Add_Update_Activity and it is working fine now, I am able to open the Add_Update_Activity on item click event now, I also did some changes in my Adapter class referring this link : http://www.codexpedia.com/android/defining-item-click-listener-for-recyclerview-in-android/ .I am Updating my code above can you please check it ones, Thanks again. – Sohail K. Shaikh Sep 06 '17 at 10:41
  • Well you are welcome, glad I helped. I'll check your code once more. And I'll also update the answer so that the solution is up there and easier to find. – Marta Sep 06 '17 at 11:00
  • I had a doubt, suppose I delete the 2nd item in recyclerview, whose adapter position is 2 then my recyclerview gets updated and my 3rd item in recycler view comes in 2nd position whose database id is 3 and adapter position becomes 2, now if I want to delete this item with database id 3, is there any method for that. as in my above code i have used a textview where i am storing the id in textview and then passing the same database id during my item click. – Sohail K. Shaikh Sep 06 '17 at 11:22