Callbacks from another class - java

I have been trying to call methods on the Main Activity from another class. But, the methods are not resolved. Check out the code.
package com.example.android.andhive_glideimagelib.activity;
import android.app.ProgressDialog;
import android.media.Image;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.android.andhive_glideimagelib.R;
import com.example.android.andhive_glideimagelib.adapter.GalleryAdapter;
import com.example.android.andhive_glideimagelib.app.AppController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint = "http://api.androidhive.info/json/glide.json";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(this);
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getApplicationContext(), images);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
fetchImages();
}
private void fetchImages() {
pDialog.setMessage("Downloading json...");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
images.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Image image = new Image();
image.setName(object.getString("name"));
JSONObject url = object.getJSONObject("url");
image.setSmall(url.getString("small"));
image.setMedium(url.getString("medium"));
image.setLarge(url.getString("large"));
image.setTimestamp(object.getString("timestamp"));
images.add(image);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
The Class,
package com.example.android.andhive_glideimagelib.model;
import java.io.Serializable;
public class Image implements Serializable {
private String name;
private String small, medium, large;
private String timestamp;
public Image() {
}
public Image(String name, String small, String medium, String large, String timestamp) {
this.name = name;
this.small = small;
this.medium = medium;
this.large = large;
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSmall() {
return small;
}
public void setSmall(String small) {
this.small = small;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getLarge() {
return large;
}
public void setLarge(String large) {
this.large = large;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
I can't call the methods of the Image class. Thanks for the help !

in the image class make it static method
example:
public static void setSmall(String small){
this.small=small;
}
in MainActivity
Image.setSmall("value");

Related

Calculation using JSON Data in RecyclerView and ToggleButton

I want to do calculation using JSON Data in RecyclerView with ToggleButton. When the toggle button is checked the value should change and when its not checked the value should change again for that particular RecyclerView row. The problem is when I click the ToggleButton, 2 other RecyclerView row's ToggleButton is also checked.
CODE:
Activity
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.gridlayout.widget.GridLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class GstPlanner extends AppCompatActivity implements GstPlanAdapter.GstPlanListener{
private static final String TAG = GstPlanner.class.getSimpleName();
List<String> dateNames = new ArrayList<String>();
private List<GstPlanList> GSTLisT;
private GstPlanAdapter mAdapter;
Context context;
Spinner ret_pending_drop, state_drop, nil_drop;
String URL, URL1;
ProgressBar progress_gst, Progress_Gst_Plan;
GridLayout grid_gst;
TextView txt_retry_gst, txt_state_gst, txt_ret_type, txt_final_gst;
Button btn_retry_gst, btn_submit_state, btn_submit;
String State_GET;
RecyclerView recyclerView1;
RelativeLayout Gst_Plan_Relative;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gst_planner);
Gst_Plan_Relative = findViewById(R.id.Gst_Plan_Relative);
recyclerView1 = findViewById(R.id.Recycler_Gst_Plan);
Progress_Gst_Plan = findViewById(R.id.Progress_Gst_Plan);
btn_submit_state = findViewById(R.id.btn_submit_state);
txt_state_gst = findViewById(R.id.txt_state_gst);
txt_ret_type = findViewById(R.id.txt_ret_type);
txt_retry_gst = findViewById(R.id.txt_retry_gst);
btn_retry_gst = findViewById(R.id.btn_retry_gst);
ret_pending_drop = findViewById(R.id.ret_pending_drop);
txt_final_gst = findViewById(R.id.txt_final_gst);
state_drop = findViewById(R.id.state_drop);
btn_submit = findViewById(R.id.btn_submit);
nil_drop = findViewById(R.id.nil_drop);
grid_gst = findViewById(R.id.grid_gst);
progress_gst = findViewById(R.id.progress_gst);
GSTLisT = new ArrayList<>();
mAdapter = new GstPlanAdapter(this, GSTLisT, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView1.setLayoutManager(mLayoutManager);
recyclerView1.setItemAnimator(new DefaultItemAnimator());
recyclerView1.addItemDecoration(new MyDividerItemDecoration(this, DividerItemDecoration.VERTICAL, 36));
recyclerView1.setAdapter(mAdapter);
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL1 = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString()+"&RType="+txt_ret_type.getText().toString()+"&NIL="+nil_drop.getSelectedItem().toString()+"&Month="+ret_pending_drop.getSelectedItem().toString();
Log.e("URL1",URL1);
Progress_Gst_Plan.setVisibility(View.VISIBLE);
fetchData();
GlobalValue.getit = true;
}
});
btn_submit_state.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString();
State_GET = state_drop.getSelectedItem().toString();
btn_submit_state.setVisibility(View.INVISIBLE);
state_drop.setVisibility(View.INVISIBLE);
progress_gst.setVisibility(View.VISIBLE);
fetchMonths();
}
});
btn_retry_gst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit_state.setVisibility(View.VISIBLE);
state_drop.setVisibility(View.VISIBLE);
}
});
}
private void fetchData() {
JsonArrayRequest request = new JsonArrayRequest(URL1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response == null) {
Toast.makeText(getApplicationContext(), "Couldn't fetch the Details! Please try again.", Toast.LENGTH_LONG).show();
return;
}
Gst_Plan_Relative.setVisibility(View.VISIBLE);
Progress_Gst_Plan.setVisibility(View.INVISIBLE);
List<GstPlanList> items = new Gson().fromJson(response.toString(), new TypeToken<List<GstPlanList>>() {
}.getType());
// adding contacts to contacts list
GSTLisT.clear();
GSTLisT.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
Progress_Gst_Plan.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage() +error.getCause());
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
Gst_Plan_Relative.setVisibility(View.INVISIBLE);
}
});
APP.getInstance().addToRequestQueue(request);
}
private void fetchMonths() {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject object = jsonArray.getJSONObject(0);
JSONArray arrayContacts = object.getJSONArray("Status");
for (int i = 0; i<arrayContacts.length(); i++) {
JSONObject contactObject = arrayContacts.getJSONObject(i);
dateNames.add(contactObject.getString("Month"));
}
spinnervalue(dateNames, ret_pending_drop);
txt_state_gst.setText(State_GET);
progress_gst.setVisibility(View.INVISIBLE);
grid_gst.setVisibility(View.VISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
public void spinnervalue(List<String> value, Spinner spinner1){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, value);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void AlertDialog(String s) {
try{
AlertDialog.Builder builder1 = new AlertDialog.Builder(GstPlanner.this);
builder1.setMessage(s);
builder1.setCancelable(true);
builder1.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}catch (
WindowManager.BadTokenException ex){
ex.printStackTrace();
}
}
#Override
public void onSubTotalUpdate(int total){
txt_final_gst.setText(String.valueOf(total));
}
RecyclerView Adapter
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GstPlanAdapter extends RecyclerView.Adapter<GstPlanAdapter.MyViewHolder>
implements Filterable {
private Context context;
private List<GstPlanList> GstPlanList;
private List<GstPlanList> GstPlanListFiltered;
private GstPlanListener listener;
int totalPrice;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView ret_month, due_date, penalty_amt;
Spinner nil_ret;
ToggleButton toggleSwitch;
public MyViewHolder(View view) {
super(view);
ret_month = view.findViewById(R.id.ret_month);
due_date = view.findViewById(R.id.due_date);
penalty_amt = view.findViewById(R.id.penalty_amt);
toggleSwitch = view.findViewById(R.id.switch_gst);
}
}
public GstPlanAdapter(Context context, List<GstPlanList> BiLLList, GstPlanListener listener ) {
this.context = context;
this.listener = listener;
this.GstPlanList = BiLLList;
this.GstPlanListFiltered = BiLLList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent1, int viewType1) {
View itemView = LayoutInflater.from(parent1.getContext())
.inflate(R.layout.gst_plan_view_item_row, parent1, false);
return new MyViewHolder(itemView);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
final GstPlanList bill = GstPlanListFiltered.get(position);
holder.nil_ret.setAdapter(categoriesAdapter);
holder.ret_month.setText(bill.getMonth());
holder.due_date.setText(bill.getDate());
holder.penalty_amt.setText(bill.getPenatly().toString());
totalPrice = 0;
for (int i = 0; i < GstPlanList.size(); i++) {
totalPrice += GstPlanList.get(i).getPenatly();
countTotal(totalPrice);
}
if (GlobalValue.getit == true) {
if (bill.getNIL().equals("YES")) {
holder.toggleSwitch.setChecked(true);
GlobalValue.getit = false;
} else {
holder.toggleSwitch.setChecked(false);
GlobalValue.getit = false;
}
}
holder.toggleSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILNO().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILYES().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
if (!holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILYES().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILNO().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
}
});
}
public void countTotal(int total){
listener.onSubTotalUpdate(total);
}
#Override
public int getItemCount() {
return GstPlanListFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
GstPlanListFiltered = GstPlanList;
} else {
List<GstPlanList> filteredList = new ArrayList<>();
for (GstPlanList row : GstPlanList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getDate().toLowerCase().contains(charString.toLowerCase()) || row.getMonth().toLowerCase().contains(charString.toLowerCase()) || row.getRType().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
GstPlanListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = GstPlanListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
GstPlanListFiltered = (ArrayList<GstPlanList>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface GstPlanListener {
// void onGstPlanSelected(GstPlanList bill);
void onSubTotalUpdate(int total);
}
}
GstPlanList
public class GstPlanList {
private String RType;
private String State;
private String NILNO;
private String NILYES;
private String Month;
private String Date;
private String NIL;
private int Penatly;
private int TODATE;
public GstPlanList() {
}
public Integer getPenatly() {
return Penatly;
}
public int getTODATE() {
return TODATE;
}
public String getNIL() {
return NIL;
}
public String getRType() {
return RType;
}
public String getState() {
return State;
}
public String getNILNO() {
return NILNO;
}
public String getNILYES() {
return NILYES;
}
public String getMonth() {
return Month;
}
public String getDate() {
return Date;
}
}

Unable to display Json data

I am trying to display json array which is inside a json object but nothing is displaying on the text view. I debugged and found that info.java class is working fine. If i am passing the simple string value(after removing the json parsing java code) in the info.java class it's working but i am unable to pass json data.
Singleton.java
package com.example.osama.recyclerthug;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class Singleton {
private static Singleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private Singleton(Context context){
mCtx = context;
mRequestQueue =getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized Singleton getInstance(Context context){
if (mInstance == null){
mInstance = new Singleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){
if (mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> request){
getRequestQueue().add(request);
}
public ImageLoader getmImageLoader(){
return mImageLoader;
}
}
...................................................................
ThugAdapter.java
package com.example.osama.recyclerthug;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ThugAdapter extends RecyclerView.Adapter<ThugAdapter.ThugHolder> {
ArrayList<Info> arrayList1;
public ThugAdapter(ArrayList<Info> arrayList){
this.arrayList1 = arrayList;
}
#NonNull
#Override
public ThugHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.appearance, viewGroup, false);
ThugHolder thugHolder = new ThugHolder(view);
return thugHolder;
}
#Override
public void onBindViewHolder(#NonNull ThugHolder thugHolder, int i) {
thugHolder.text.setText(arrayList1.get(i).getTxt1());
thugHolder.text2.setText(arrayList1.get(i).getTxt2());
/* thugHolder.image.setImageURI(arrayList.get(i).getImageUri());*/
}
#Override
public int getItemCount() {
return arrayList1.size();
}
public class ThugHolder extends RecyclerView.ViewHolder{
TextView text,text2;
ImageView image;
public ThugHolder(#NonNull View itemView) {
super(itemView);
text = itemView.findViewById(R.id.textView);
text2 = itemView.findViewById(R.id.textView2);
image = itemView.findViewById(R.id.imageView);
}
}
}
............................................................................
Info.java
package com.example.osama.recyclerthug;
import android.net.Uri;
public class Info {
private String txt1,txt2;
// private Uri imageuri;
public Info(String txt1, String txt2/*, Uri imageuri*/){
this.setTxt1(txt1);
this.setTxt2(txt2);
/* this.setImageUri(imageuri);*/
}
public String getTxt1() {
return txt1;
}
public void setTxt1(String txt1) {
this.txt1 = txt1;
}
public String getTxt2() {
return txt2;
}
public void setTxt2(String txt2) {
this.txt2 = txt2;
}
/*public Uri getImageUri() {
return imageuri;
}
public void setImageUri(Uri imageuri) {
this.imageuri = imageuri;
}*/
}
........................................................
BackgroundTask.java
package com.example.osama.recyclerthug;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class BackgroundTask {
Context context;
ArrayList<Info> arrayList;
String json_url = "http://cc97cf60.ngrok.io/api/note/";
public BackgroundTask(Context context){
this.context = context;
}
public ArrayList<Info> getArrayList(){
arrayList = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray ;
try {
jsonArray = response.getJSONArray("objects");
int i;
for (i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
/* Uri b = Uri.parse(jsonObject.getString("image")); //Type casting string to uri*/
String a = jsonObject.getString("title");
String b = jsonObject.getString("body");
Info info = new Info(a,b);
arrayList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
return arrayList;
}
}
..............................................
MainActivity.java
package com.example.osama.recyclerthug;
import android.app.DownloadManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
ThugAdapter thugAdapter;
BackgroundTask backgroundTask;
ArrayList<Info> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
backgroundTask = new BackgroundTask(this);
arrayList = new ArrayList<>();
arrayList= backgroundTask.getArrayList();
thugAdapter = new ThugAdapter(arrayList);
recyclerView.setAdapter(thugAdapter);
}
}
Edit: Below is the json data:
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 2
},
"objects": [
{
"body": "Breaking News:\r\nOsama Abrar is Iron Man.",
"created_at": "2018-12-08T08:40:59.949776",
"id": 1,
"image": "https://wonderfulengineering.com/wp-content/uploads/2016/01/iron-man-wallpaper-6.jpg",
"resource_uri": "/api/note/1/",
"title": "Iron Man"
},
{
"body": "Will Iron Man aka Osama Abrar survive?",
"created_at": "2018-12-08T08:41:40.279677",
"id": 2,
"image": "https://marciokenobi.files.wordpress.com/2013/03/iron_man.jpg",
"resource_uri": "/api/note/2/",
"title": "End Game"
}
]
}
JSON parsing is OK but you can't retrieve your data like this because you used Volley in asynchronous mode. It means that you can't assume that data will be retrieved as soon as you put the request in the queue. Maybe the queue is very long and your request can be sent later. So, when you tried to retrieve your data, you've seen that your arrayList is null, and it's normal. To deal with the asynchronous way, you have to tell Volley : "tell me when you've retrieved data". And you can do this with a listener.
Here is an example.
public interface Listener {
void onDataReceived(ArrayList<Info> list);
void onError(int error);
}
BackgroundTask
public class BackgroundTask {
Context context;
ArrayList<Info> arrayList;
Listener mListener; // listener to retrieve data
String json_url = "http://cc97cf60.ngrok.io/api/note/";
public BackgroundTask(Context context, Listener listener) {
this.context = context;
mListener = listener;
}
public void getArrayList() { // no return needed
arrayList = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray;
try {
jsonArray = response.getJSONArray("objects");
int i;
for (i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
/* Uri b = Uri.parse(jsonObject.getString("image")); //Type casting string to uri*/
String a = jsonObject.getString("title");
String b = jsonObject.getString("body");
Info info = new Info(a, b);
arrayList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
// if listener has been set, send data
if (mListener != null) {
mListener.onDataReceived(arrayList);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// if listener has been set, send error
if (mListener != null) {
mListener.onError(error.networkResponse.statusCode);
}
}
});
Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
}
}
In your MainActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
backgroundTask = new BackgroundTask(this, new Listener() {
#Override
public void onDataReceived(ArrayList<Info> list) {
thugAdapter = new ThugAdapter(list);
recyclerView.setAdapter(thugAdapter);
}
#Override
public void onError(int error) {
}
});
backgroundTask.getArrayList();
}
And that is !

ItemClickListener not working in Fragment RecyclerView with onclick

I've been following this tutorial: Tutorial
To make a json recyclerviewer with onclick, but i wanted to use Fragments instead of activities.
I've figured everything out until the point of the onClick.
My problem is the setOnItemClickListener is not taking my getActivity()
I've tried so much, but i just cant see the bright light.
If anyone could help me out that would be totally awesome!
Me only real problem is that the getActivity is giving a red line in the:
fNieuwsAdapter.setOnItemClickListener(getActivity());
NieuwsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import java.util.ArrayList;
public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
public static final String EXTRA_URL = "nieuwsImageUrl";
public static final String EXTRA_HEADING = "nieuwsHeading";
public static final String EXTRA_CONTENT = "nieuwsContent";
private RecyclerView fNieuwsRecyclerView;
private NieuwsAdapter fNieuwsAdapter;
private ArrayList<NieuwsItem> fNieuwsList;
private RequestQueue fNieuwsQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
fNieuwsRecyclerView.setHasFixedSize(true);
fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fNieuwsList = new ArrayList<>();
fNieuwsQueue = Volley.newRequestQueue(getActivity());
parseJSON();
return view;
}
private void parseJSON() {
String url = "urlissecretsorry<3butthejsonparsingworks";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public String nieuwsImageUrl;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
JSONArray attachArray = hit.getJSONArray("attachments");
for (int a = 0; a < attachArray.length(); a++) {
JSONObject attach = attachArray.getJSONObject(a);
nieuwsImageUrl = attach.getString("url");
}
String nieuwsHeading = hit.getString("title");
String nieuwsExcerpt = hit.getString("excerpt");
String nieuwsContent = hit.getString("content");
nieuwsExcerpt = html2text(nieuwsExcerpt);
fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
}
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
fNieuwsAdapter.setOnItemClickListener(getActivity());
fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
fNieuwsQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
NieuwsItem clickedItem = fNieuwsList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
startActivity(detailIntent);
}
public String html2text(String html) {
try {
return Jsoup.parse(html).text();
} catch (Exception ignored) {
return "";
}
}
}
NieuwsItem.java
public class NieuwsItem {
private String nieuwsImageUrl;
private String nieuwsHeading;
private String nieuwsExcerpt;
private String nieuwsContent;
public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
nieuwsImageUrl = imageUrl;
nieuwsHeading = heading;
nieuwsExcerpt = excerpt;
nieuwsContent = content;
}
public String getImageUrl(){
return nieuwsImageUrl;
}
public String getHeading(){
return nieuwsHeading;
}
public String getExcerpt(){
return nieuwsExcerpt;
}
public String getContent(){
return nieuwsContent;
}
}
NieuwsAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {
private Context NieuwsContext;
private ArrayList<NieuwsItem> NieuwsList;
private OnItemClickListener NieuwsListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
NieuwsListener = listener;
}
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
#NonNull
#Override
public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
return new NieuwsViewHolder(v);
}
#Override
public void onBindViewHolder(NieuwsViewHolder holder, int position) {
NieuwsItem currentitem = NieuwsList.get(position);
String ImageUrl = currentitem.getImageUrl();
String Heading = currentitem.getHeading();
String Excerpt = currentitem.getExcerpt();
holder.NieuwsTextViewHeading.setText(Heading);
holder.NieuwsTextViewExcerpt.setText(Excerpt);
Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
}
#Override
public int getItemCount() {
return NieuwsList.size();
}
public class NieuwsViewHolder extends RecyclerView.ViewHolder {
public ImageView NieuwsImageView;
public TextView NieuwsTextViewHeading;
public TextView NieuwsTextViewExcerpt;
public NieuwsViewHolder(#NonNull View itemView) {
super(itemView);
NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra("EXTRA_URL");
String creatorName = intent.getStringExtra("EXTRA_HEADING");
String likeCount = intent.getStringExtra("EXTRA_CONTENT");
ImageView imageView = findViewById(R.id.nieuws_detail_image);
TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
TextView textViewContent = findViewById(R.id.nieuws_detail_content);
Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
textViewHeading.setText(creatorName);
textViewContent.setText("Likes: " + likeCount);
}
}
You cant use NieuwsAdapter.setOnItemClickListener(getActivity()); , unless your activity implements OnItemClickListener interface, but im seeing that your fragment implements OnItemClickListener, so you can use the fragment instead like this :
fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);
And by the way, you are sending the data via intent with :
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
You have to get them with the same parameters (remove the ""):
String imageUrl = intent.getStringExtra(EXTRA_URL);
String creatorName = intent.getStringExtra(EXTRA_HEADING);
String likeCount = intent.getStringExtra(EXTRA_CONTENT);
Hope this helps
change
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
to
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
this.NieuwsContext = context;
this.NieuwsList = nieuwslist;
this.NieuwsListener = mOnClickListener;
}
and this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
change to
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwsListener.onItemClick(int position);
}
});
and then in fragment You can do it like this
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position)
{
//DoSomethingHere
}
});

Attempt to invoke virtual method (null object reference)

Currently, I'm developing a media player, and I want hide a element when audio finishes. But when it happens, the app crash with this error: Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference. Check my current code:
meplayer.java
package etes.xddda.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class meplayer extends Activity {
public static MediaPlayer mediaPlayer;
public LinearLayout menu_dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_dialog = findViewById(R.id.menu_dialog);
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public LinearLayout menu_dialog;
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
menu_dialog.setVisibility(View.GONE);
}
});
mediaPlayer.start();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
RecyclerViewAdapter
package etes.xddda.music;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
Context mContext;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
meplayer media;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(Context mContext, List<mList> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void onClick(View view) {
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
media = new meplayer();
media.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private TextView tv_url;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = (TextView) itemView.findViewById(R.id.name_list);
tv_author = (TextView) itemView.findViewById(R.id.author_list);
img = (ImageView) itemView.findViewById(R.id.img_contact);
}
}
}
fragmentList
package etes.xddda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
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.List;
public class fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "https://pastebin.com/raw/fG3zd40U";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(getContext(), lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
MainActivity
package etes.xddda.music;
import android.annotation.SuppressLint;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
private String player_status = "playing";
private ImageButton player_img;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
meplayer.pauseAudio();
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
meplayer.startAudio();
player_status = "playing";
}
}
});
//menu_dialog.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0,0,0,0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
}
mList
package etes.xddda.music;
public class mList {
private String Name;
private String Author;
private String URL;
private int Photo;
public mList() {
}
public mList(String name, String phone, String url, int photo) {
Name = name;
Author = phone;
URL = url;
Photo = photo;
}
//Get User
public String getName() {
return Name;
}
public String getPhone() {
return Author;
}
public String getURL() {
return URL;
}
public int getPhoto() {
return Photo;
}
//Setter
public void setName(String name) {
Name = name;
}
public void setPhone(String phone) {
Author = phone;
}
public void setURL(String url) {
URL = url;
}
public void setPhoto(int photo) {
Photo = photo;
}
}
There are no errors in this script, the app just crash when audio finishes. The problem is related to line menu_dialog.setVisibility(View.GONE); and I have already defined menu_dialog in onCreate. So, can you help me?
P.S.: menu_dialog belongs to activity_main.xml
Thank you!
Remove the local variable menu_dialog that you have defined inside the OnCompletionListener:
package etes.xddda.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class meplayer extends Activity {
public static MediaPlayer mediaPlayer;
public LinearLayout menu_dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_dialog = findViewById(R.id.menu_dialog);
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//public LinearLayout menu_dialog; REMOVE THIS
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
menu_dialog.setVisibility(View.GONE);
}
});
mediaPlayer.start();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

live search with MySQL database using Json and display result in listview android

i am working of live search with MySQL, JSON. its working fine with local array values. but not working with MySQL. my concern is when user start typing it has to search from data base and show it in listview. bellow is my Adapter for search
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import zesteve.com.myapplication.R;
import zesteve.com.myapplication.Search;
import zesteve.com.myapplication.VendProfileActivity;
/**
* Created by Ravi Shankar on 6/22/2017.
*/
public class SearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Search> vendersearchlist = null;
private ArrayList<Search> arraylist;
public SearchAdapter(Context context,
List<Search> vendersearchlist) {
mContext = context;
this.vendersearchlist = vendersearchlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Search>();
this.arraylist.addAll(vendersearchlist);
}
public class ViewHolder {
TextView id;
TextView vname;
}
#Override
public int getCount() {
return vendersearchlist.size();
}
#Override
public Search getItem(int position) {
return vendersearchlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.search_item_list, null);
// Locate the TextViews in listview_item.xml
//holder.id = (TextView) view.findViewById(R.id.id);
holder.vname = (TextView) view.findViewById(R.id.autoCompleteTextView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(Search.get(position).getRank());
holder.vname.setText(vendersearchlist.get(position).getVname());
// Listen for ListView Item Click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, VendProfileActivity.class);
// Pass all data rank
intent.putExtra("Vend_Id",
(vendersearchlist.get(position).getId()));
// Pass all data country
intent.putExtra("Vend_Name",
(vendersearchlist.get(position).getVname()));
// Pass all data population
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
vendersearchlist.clear();
if (charText.length() == 0) {
vendersearchlist.addAll(arraylist);
} else {
for (Search sl : arraylist) {
if (sl.getVname().toLowerCase(Locale.getDefault())
.contains(charText)) {
vendersearchlist.add(sl);
}
}
}
notifyDataSetChanged();
}
}
AND POJO
public class Search {
private int id;
private String vname;
public Search(int id, String vname) {
this.id = id;
this.vname = vname;
}
public int getId() {
return this.id;
}
public String getVname() {
return this.vname;
}
}
And my SearchActivity.java
import android.content.res.Resources;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import zesteve.com.myapplication.adapter.SearchAdapter;
import zesteve.com.myapplication.adapter.VenderAdapter;
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
private EditText Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
int[] id;
String[] vname;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
listview = (ListView) findViewById(R.id.listview);
Vendname = (EditText) findViewById(R.id.searchitem);
Vendname.setHint("Search "+catname+" in "+city);
//fetch data from server in json
String vsearch = Vendname.getText().toString();
prepareVender(vsearch);
// Pass results to ListViewAdapter Class
adapter = new SearchAdapter(this, vendersearchlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Locate the EditText in listview_main.xml
Vendname.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = Vendname.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void prepareVender(String sText){
AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/vend_list.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
try{
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object= array.getJSONObject(i);
Search vender = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(vender);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(sText);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Please comment if you have any doubts.
if Somebody looking for same Solution. bellow is my code
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
SearchView Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
ArrayList<Search> filteredSearchResults = new ArrayList<Search>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
progressDialog = new ProgressDialog(Search_vender.this);
progressDialog.setCancelable(false);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
//Toast.makeText(Search_vender.this,catid + city,Toast.LENGTH_LONG).show();
listview = (ListView) findViewById(R.id.listview);
Vendname = (SearchView) findViewById(R.id.searchitem);
Vendname.setQueryHint("Search "+catname+" in "+city);
Vendname.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
//Toast.makeText(Search_vender.this, String.valueOf(hasFocus),Toast.LENGTH_SHORT).show();
}
});
Vendname.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.length() > 2){
listview.setVisibility(View.VISIBLE);
GetDataVender gv = (GetDataVender) new GetDataVender().execute(newText);
}else{
listview.setVisibility(View.INVISIBLE);
}
return false;
}
});
}
public void filterSearchArray(String newText){
String pName;
filteredSearchResults.clear();
for (int i = 0; i < vendersearchlist.size(); i++)
{
pName = vendersearchlist.get(i).getVname().toLowerCase();
if ( pName.contains(newText.toLowerCase()))
{
filteredSearchResults.add(vendersearchlist.get(i));
}
}
}
class GetDataVender extends AsyncTask<String, Void, String>{
String textsearch;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading Please Wait...");
showDialog();
}
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/autosearch.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
this.textsearch = strings[0];
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
Search catagory = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(catagory);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null && result.equalsIgnoreCase("Exception Caught")){
Toast.makeText(Search_vender.this, "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
hideDialog();
}else{
filterSearchArray(textsearch);
listview.setAdapter(new SearchAdapter(Search_vender.this,filteredSearchResults));
hideDialog();
}
//hideDialog();
//adapter.notifyDataSetChanged();
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
it works when user stat search from second character.

Categories