my recyclerview has an adapter that is null - java

i want to get data from a edit text and give to adapter but adapter is null
data isnt null because i can toast it but it doesnt show in my model
My question now is: when is an adapter null in RecyclerView and what might be the solution to the problem?
Please help a green developer; this is my first app. Any suggestion would be welcomed.
this is my Main Activity
public class MainActivity extends AppCompatActivity {
public static final int request_code=1001;
RecyclerView recyclerView;
NoteListAdapter noteListAdapter;
List<Notes> Notes_list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.mainAc_recyclerview_notes);
noteListAdapter = new NoteListAdapter(this,Notes_list);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(noteListAdapter);
Button newnote= findViewById(R.id.mainAc_button_new);
newnote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,GenerateNote.class);
startActivityForResult(intent,request_code);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==request_code && resultCode==RESULT_OK && data!=null){
String name=data.getExtras().getString(result_name);
String description=data.getExtras().getString(result_description);
Notes notes=new Notes();
notes.setSnTitle(name);
notes.setSnDescription(description);
NoteListAdapter adapter=new NoteListAdapter(this,Notes_list);
adapter.addNote(notes);
Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}
}
}
adapter
public class NoteListAdapter extends RecyclerView.Adapter<NoteListAdapter.notesViewHolder> {
#NonNull
private Context context;
private List<Notes> notes_list=new ArrayList<>();
public NoteListAdapter(Context context, List<Notes> notes_list) {
this.context = context;
this.notes_list=notes_list;
}
#Override
public NoteListAdapter.notesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_sample_note, parent, false);
return new notesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NoteListAdapter.notesViewHolder holder, int position) {
holder.bindNotes(notes_list.get(position));
}
#Override
public int getItemCount() {
return notes_list.size();
}
public void addNote(Notes notes){
notes_list.add(notes);
notifyItemInserted(1);
}
public class notesViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private TextView description;
notesViewHolder(#NonNull View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.sn_textview_title);
description = (TextView)itemView.findViewById(R.id.sn_textview_description);
}
public void bindNotes(Notes notes) {
title.setText(notes.getSnTitle());
description.setText(notes.getSnDescription());
}
}
}
and activity for result
public class GenerateNote extends AppCompatActivity {
public static final String result_name="result_name";
public static final String result_description="result_description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generate_note);
final EditText name=findViewById(R.id.gn_edittext_name);
final EditText description=findViewById(R.id.gn_edittext_family);
Button save=findViewById(R.id.gn_button_save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra(result_name,name.getText().toString());
intent.putExtra(result_description,description.getText().toString());
setResult(RESULT_OK,intent);
finish();
}
});
}
}

change below code in onActivityResult() ;)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==request_code && resultCode==RESULT_OK && data!=null){
String name=data.getExtras().getString(result_name);
String description=data.getExtras().getString(result_description);
Notes notes=new Notes();
notes.setSnTitle(name);
notes.setSnDescription(description);
Notes_list.add(notes); // change here
adapter.notifyDataSetChanged(); // change here
Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}
}

You have a method in the adapter to add Note. So, you can directly use that method Adapter.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==request_code && resultCode==RESULT_OK && data!=null){
String name=data.getExtras().getString(result_name);
String description=data.getExtras().getString(result_description);
Notes notes=new Notes();
notes.setSnTitle(name);
notes.setSnDescription(description);
adapter.addNote(notes); // Use Adapter method
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}
}

Related

recyclerview item click listener with sqlite java

I would like to get data from the box which click on on the recycler view to go into a another activity to display.
I have tried to flow this video https://www.youtube.com/watch?v=7GPUpvcU1FE&t=399s&ab_channel=PracticalCoding i dont understand at 6:16.
Also https://www.youtube.com/watch?v=VQKq9RHMS_0&ab_channel=Stevdza-San i cannot get the data to pass to the new activity.
Main code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_staff_home);
DB=new mainTextDBHelper(this);
recyclerView=findViewById(R.id.recyclerview);
Title=new ArrayList<>();
description=new ArrayList<>();
radiogroup=new ArrayList<>();
adapter=new recyclerviewAdapter(this,Title,description,radiogroup,listener);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
displaydata();
setOnClickListner();
private void setOnClickListner() {
listener=new recyclerviewAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent intent=new Intent(getApplicationContext(),cardviewclickon.class);
intent.putExtra("Title",Title.get(position));
startActivity(intent);
}
};
}
private void displaydata() {
Cursor cursor=DB.getdata();
if(cursor.getCount()==0){
Toast.makeText(staff_home.this,"No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}else{
while(cursor.moveToNext())
{
Title.add(cursor.getString(1));
description.add(cursor.getString(2));
radiogroup.add(cursor.getString(3));
}
}
}
recyclerview Adapter code
public class recyclerviewAdapter extends RecyclerView.Adapter<recyclerviewAdapter.MyViewHolder>{
private Context context;
private ArrayList Title_id,description_id,radiogroup_id;
private RecyclerViewClickListener listener;
public recyclerviewAdapter(Context context, ArrayList title_id, ArrayList description_id, ArrayList radiogroup_id,RecyclerViewClickListener listener) {
this.context = context;
Title_id = title_id;
this.description_id = description_id;
this.radiogroup_id = radiogroup_id;
this.listener=listener;
}
#NonNull
#Override
public recyclerviewAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.userentry,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull recyclerviewAdapter.MyViewHolder holder, int position) {
holder.Title_id.setText(String.valueOf(Title_id.get(position)));
holder.description_id.setText(String.valueOf(description_id.get(position)));
holder.radiogroup_id.setText(String.valueOf(radiogroup_id.get(position)));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(context,cardviewclickon.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return Title_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Title_id,description_id,radiogroup_id;
CardView cardView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
Title_id=itemView.findViewById(R.id.textTitle);
description_id=itemView.findViewById(R.id.textdescription);
radiogroup_id=itemView.findViewById(R.id.textsrverity);
cardView=itemView.findViewById(R.id.card);
new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onClick(view,getAdapterPosition());
}
};
}
#Override
public void onClick(View view) {
listener.onClick(view,getAdapterPosition());
}
}
public interface RecyclerViewClickListener{
void onClick(View v,int position);
}
}
If you want to pass data from one activity to other you can use PutExtra() method of the Intent class As I can see you are doing everything pretty much well but you have to catch these extra from the class you are passing like:- I want to pass data from recyclerView to CardViewClass I can do it like:-
In RecyclerView.java file:-
public void sendDataAndOpen(String title) {
Intent intent = new Intent(getApplicationContext(), CardViewClass.class);
intent.putExtraString("Title",Title); // You can use putExtra to put any datatype
startActivity(intent);
}
In CardViewClass.java file (Lets catch our passing data):-
public void onCreate(...) {
....
String title = getIntent().getExtraString("Title") // You can also use ExtraPut and // Must use Same Id
// Use data as you want
.....
}

How to check what the user clicked on uninstall dialog box created using intent in android?

i am trying create an app that is capable of uninstalling the other installed apps . So when i am using uninstall intent the dialog box opened ask for Ok or cancel. so how can i get informed whether the user selected ok or cancel as i need to hide the the uninstall button that is pressed. Assigned as button present in public class viewholder at end of the code
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
MainActivity mainActivity=new MainActivity();
private Context mContext;
List<Drawable> images;
List<String> titles;
List<String> apps;
LayoutInflater inflater;
public void uninstallAPK(String apkPackageName) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + apkPackageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivity(intent);
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
launchBrowser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchBrowser.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivity(launchBrowser);
mainActivity.finish();
}
public Adapter(Context ctx, List<String> titles, List<Drawable>
images,List<String> apps){
this.titles =titles;
this.images = images;
this.apps = apps;
this.inflater =LayoutInflater.from(ctx);
mContext = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
View view = inflater.inflate(R.layout.custom_grid_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int
position) {
holder.title.setText(titles.get(position));
holder.gridIcon.setImageDrawable(images.get(position));
}
#Override
public int getItemCount() {
return titles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView gridIcon;
TextView title;
Button button;
Button button3;
public ViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.textView);
gridIcon = itemView.findViewById(R.id.imageView2);
button = itemView.findViewById(R.id.button);
button3 = itemView.findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uninstallAPK(apps.get(getAdapterPosition()));
//want to hide the button if ok is pressed otherwise want
to show the button
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ParseQuery<ParseObject> linkwa = new
ParseQuery<ParseObject>("package");
linkwa.whereEqualTo("packid",
apps.get(getAdapterPosition()));
linkwa.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects,
ParseException e) {
if(e==null && objects.size()>0){
for (ParseObject object:objects){
goToUrl(object.getString("link"));
}
}
}
});
}
});
}
}
}
There is actually workaround that you can give a try
StartActivityFotResult which will ensure you will get the callback inside onActivityResult
public void uninstallAPK(String apkPackageName) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + apkPackageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivityForResult(intent, 12345);
}
Now you can check the Result-Code whether it is a success or not RESULT_OK or RESULT_CANCELLED
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1234) {
if(resultCode == Activity.RESULT_OK){
//Deleted
}
if (resultCode == Activity.RESULT_CANCELED) {
//Dismissed
}
}
}//onActivityResult
2.1. If the above-mentioned solution did not work then
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1234) {
if (appInstalledOrNot("required_app_package_name")){
// Dismissed
}else {
//Deleted
}
}
}//onActivityResult
private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
PS. Checking if an app is installed or not is taken from here
Don't really know how is your implementation, but ideally I would have two button. One for cancel another for uninstall. And I would have set clicklistener on both of the button. So, whenever, the onclickListener is executed, means user pressed the button of the dialog box. So, first thing, I would dissmiss the dialog, second thing based on the button user clicked
public void onClick(View v){
if(v.getId == R.id.btn_dialog_uninstall){
uninstallPackage("package_name");
dialog.dissmiss();
}else{
dialog.dissmiss(); // user pressed cancelled;
}
hope that helps.

How to start camera from fragment in Android

I need a camera function in my CameraFragment.java file. I already have the code for the camera and it is working in a empty application (when I put it in my MainActivity), but I don't know where to put the code in my CameraFragment.java.
I am really a beginner with Android Studio, but I couldn't find the answer on the internet. Also new on Stack Overflow.
CameraFragment.java
public class CameraFragment extends Fragment{
public static final String EXTRA_INFO = "default";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_camera, container, false);
}
}
AND I NEED THIS CODE IN MY CameraFragment FILE:
public class MainActivity extends AppCompatActivity {
private Button btnCapture;
private ImageView imgCapture;
private static final int Image_Capture_Code = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_camera);
btnCapture =(Button)findViewById(R.id.btnTakePicture);
imgCapture = (ImageView) findViewById(R.id.capturedImage);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == Image_Capture_Code) {
if (resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
imgCapture.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
}
}
Let me know how this works for you. Comment if you need more help setting this up.
public class CameraFragment extends Fragment {
public static final String EXTRA_INFO = "default";
private Button btnCapture;
private ImageView imgCapture;
private static final int Image_Capture_Code = 1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_camera, container, false);
btnCapture =(Button) view.findViewById(R.id.btnTakePicture);
imgCapture = (ImageView) view.findViewById(R.id.capturedImage);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Image_Capture_Code) {
if (resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
imgCapture.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();
}
}
}}
In fragment use same as activity but make method public
try this code
public class ChatFragment extends Fragment {
private RecyclerView chatRecylerview;
View view;
ChatUserlistAdapter userlistAdapter;
LinearLayoutManager manager;
ArrayList<HashMap<String, String>> userDetail = new ArrayList<>();
HashMap<String, String> data;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_chat, container, false);
btnCapture =(Button)view.findViewById(R.id.btnTakePicture);
imgCapture = (ImageView)view.findViewById(R.id.capturedImage);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Image_Capture_Code) {
if (resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
imgCapture.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
}
}

Trying to call method from MainActivity in Another Activity it is me leading to error

I have Recycler ListView which I show in MainActivity and the first item it is as selected, I have done to click for another items but the last stays clicked and when I try to take this recycler view to show me in next Activity it doesn't work.
The first item it is selected but I have a click method which when click an image makes as selected but when I click a new image this works but the first item stays as selected so continues for others images. I want only a image to be selected.
I don't want to write twice the same code.
Is it good if I have a class only for this method which I can use everytime I want.
The id of recycler view list it is the same on both xml's.
If you have any suggestion for my question please let me know.
This is the adapter for the RecyclerView.
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem;
private ArrayList<Integer> mImages = new ArrayList<>();
private ArrayList<String> mSearchUrl = new ArrayList<>();
private Context mContext;
public ListViewAdapter(ArrayList<Integer> images, ArrayList<String> SearchUrl, Context context) {
mImages = images;
mContext = context;
mSearchUrl = SearchUrl;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
selectedItem = 0;
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
Glide.with(mContext).load(mImages.get(i))
.into(viewHolder.image);
viewHolder.searchUrl.setText(mSearchUrl.get(i));
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
selectedItem = i;
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView searchUrl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.ivEngine);
searchUrl = itemView.findViewById(R.id.ivEngineText);
}
}
}
This is the method in MainActivity.class
public void intSearch() {
mImages.add(R.drawable.s_bing);
mSearchUrl.add("https://www.bing.com/search?q=");
mImages.add(R.drawable.s_google);
mSearchUrl.add("https://www.google.com/search?q=");
mImages.add(R.drawable.s_yahoo);
mSearchUrl.add("www.yahoo.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.lvEngines);
recyclerView.setLayoutManager(layoutManager);
ListViewAdapter adapter = new ListViewAdapter(mImages, mSearchUrl, this);
recyclerView.setAdapter(adapter);
}
This is the button which takes to another activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
Cursor data = mDatabaseHelper.getData();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("name", newEntry);
intent.putExtra("test", mSearchUrl.get(0));
startActivityForResult(intent, 2);
}
});
This is the another activity
public class ActivitySearchEngine extends Activity implements
SwipeRefreshLayout.OnRefreshListener {
public ImageView mHome;
public EditText searchPlugin;
public WebView webView;
Button btnSearch;
public ImageButton clearSearch, exitButton;
public ImageView favIcon;
public ProgressBar loadIcon;
String text;
SwipeRefreshLayout refreshLayout;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
private String selectedSearchUrl;
RecyclerView mListView;
MainActivity mainActivity = new MainActivity();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
mHome = findViewById(R.id.imgBtnHome);
searchPlugin = findViewById(R.id.etSearch);
webView = findViewById(R.id.webView);
clearSearch = findViewById(R.id.btnClearSearch);
btnSearch = findViewById(R.id.btnSearch);
favIcon = findViewById(R.id.imgViewFavIcon);
loadIcon = findViewById(R.id.progressBarIcon);
exitButton = findViewById(R.id.imgBtnStopLoad);
refreshLayout = findViewById(R.id.refreshLayout);
mListView = findViewById(R.id.lvEngines);
refreshLayout.setOnRefreshListener(this);
mDatabaseHelper = new DatabaseHelper(this);
mainActivity.intSearch(); // Here it is the error
Activity.ActivitySearchEngine}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("test");
searchPlugin.setText(selectedName);
loadIcon.setVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("www.bing.com/search?=" + selectedName);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
favIcon.setImageBitmap(icon);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadIcon.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
try {
if (loadIcon.getVisibility() == View.VISIBLE) {
loadIcon.setVisibility(View.GONE);
favIcon.setVisibility(View.VISIBLE);
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
exitButton.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRefresh();
}
});
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
searchPlugin.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
processButtonByTextLength();
}
});
mHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText(null);
finish();
}
});
clearSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText("");
}
});
public void processButtonByTextLength() {
String inputText = searchPlugin.getText().toString();
if(inputText.length() > 0) {
btnSearch.setVisibility(View.VISIBLE);
mHome.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.VISIBLE);
loadIcon.setVisibility(View.GONE);
exitButton.setVisibility(View.GONE);
} else if(inputText.length() == 0) {
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
clearSearch.setVisibility(View.GONE);
}
}
#Override
public void onRefresh() {
webView.reload();
refreshLayout.setRefreshing(false);
}
}
This is the photo with RecyclerView at MainActivity.class
Photo of another Activity

How to login Facebook using nested fragment in Android

I have nested fragment like the following.
MainActivity
FragmentA
FragmentA1
FragmentA3
FragmentA2
FragmentB
FragmentB1
I want to login facebook from FragmentA3. But can not.
In FragmentA3, my app stop in onResume after called onActivityResult.
What should I do?
FragmentA3
public class FragmentA3 extends Fragment {
public static final String TAG = FragmentA3.class.getCanonicalName();
private UiLifecycleHelper mFbSdkUiHelper;
private OnLoggedListener mCallback;
private final List<String> permissions;
public OthersFBLogin() {
// Required empty public constructor
permissions = Arrays.asList("basic_info", "email");
}
public interface OnLoggedListener {
//Callback to notify about login success.
public void onLoginSuccess();
}
private final Session.StatusCallback mSessionCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
Log.d(TAG,"onSessionStateChange");
if (state.isOpened()) {
mCallback.onLoginSuccess();
} else if (state.isClosed()) {
if (session != null) {
session.closeAndClearTokenInformation();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG,"onCreate");
super.onCreate(savedInstanceState);
mFbSdkUiHelper = new UiLifecycleHelper(getActivity(), mSessionCallback);
mFbSdkUiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG,"onCreateView");
View rootView = inflater.inflate(R.layout.others_fblogin, container, false);
LoginButton loginButton = (LoginButton) rootView.findViewById(R.id.login_button);
loginButton.setFragment(this);
loginButton.setReadPermissions(permissions);
return rootView;
}
#Override
public void onAttach(Activity activity) {
Log.d(TAG,"onAttach");
super.onAttach(activity);
try {
mCallback = (OnLoggedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnLoggedListener in order to use this fragment");
}
}
#Override
public void onResume() {
Log.d(TAG,"onResume");
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
mFbSdkUiHelper.onResume();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
mFbSdkUiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
Log.d(TAG,"onPause");
super.onPause();
mFbSdkUiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mFbSdkUiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG,"onSaveInstanceState");
super.onSaveInstanceState(outState);
mFbSdkUiHelper.onSaveInstanceState(outState);
}
}
LogCat
D/com.example.sample.FragmentA3 ﹕ onAttach
D/com.example.sample.FragmentA3 ﹕ onCreate
D/com.example.sample.FragmentA3 ﹕ onCreateView
D/com.example.sample.FragmentA3 ﹕ onResume
D/dalvikvm ﹕ GC_FOR_ALLOC freed 764K, 10% free 7977K/8816K, paused 3ms, total 6ms
W/GooglePlayServicesUtil ﹕ Google Play services is missing.
D/com.example.sample.FragmentA3 ﹕ onPause
D/com.example.sample.FragmentA3 ﹕ onSessionStateChange
W/EGL_emulation ﹕ eglSurfaceAttrib not implemented
I/Choreographer ﹕ Skipped 174 frames! The application may be doing too much work on its main thread.
D/com.example.sample.MainActivity﹕ onActivityResult
D/com.example.sample.FragmentA ﹕ onActivityResult
D/com.example.sample.FragmentA3 ﹕ onActivityResult
D/com.example.sample.FragmentA3 ﹕ onResume
Please try this solution:
public class FragmentA3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Fragment fragmentA1 = this.getParentFragment();
Fragment fragmentA = fragmentA1.getParentFragment();
loginButton.setFragment(fragmentA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
mFbSdkUiHelper.onActivityResult(requestCode, resultCode, data);
}
}
public class FragmentA1 extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mFragmentA3 !=null)
mFragmentA3.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
public class FragmentA extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mFragmentA1 !=null)
mFragmentA1.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
Step 1: Add the below code in the fragment.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
context = getContext();
FacebookSdk.sdkInitialize(context);
View view = inflater.inflate(R.layout.fragment_facebook_sign_in, container, false);
}
Step 2: Handle the callback of facebook.
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String email = object.getString("email");
String firstName = object.getString("first_name");
String lastName = object.getString("last_name");
profile_link = object.getString("link");
String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
Utility.logMe("\nFacebook_user_mail:"+email +"\nFacebook_user_Fname:"+firstName+"\nFacebook_user_Lname:"+lastName+"\nFacebook_user_Image:"+profilePicUrl+"\nProfile_link:"+profile_link);
if(email != null && email.length()> 0)
{
LoginManager.getInstance().logOut();
signUpFacebook(firstName, lastName, email, profilePicUrl, profile_link);
}
else {
Toast.makeText(getActivity(), "Email not present to login", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Email Not Exist for this user on Facebook.", Toast.LENGTH_LONG).show();
progressDialog = new ProgressDialog(getContext());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,link,name,email,birthday,gender,first_name,last_name,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
Step 3:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
//displayMessage(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
Step 4:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
Step 5:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Step 6:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
for (Fragment fragmento : allFragments) {
if (fragmento instanceof TwitterSignIn) {
((TwitterSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
if (fragmento instanceof GooglePlusSignIn) {
((GooglePlusSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
if (fragmento instanceof FacebookSignIn) {
((FacebookSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
}
}

Categories

Resources