My program is designed to search the database for the specific name entered, then the program will only display the row of the specific name. However, my code is unable to display the specific data. I have tried many kind of ways but it is unable to solve my problem. My php code is as below:
<?php
$con = mysql_connect('mysql17.000webhost.com', 'a2634311_minzhe', 'MZRules0118');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a2634311_gdp", $con);
$result = mysql_query("SELECT * FROM groupdesign");
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
My activity code is as below:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
public class PatientLocation extends ActionBarActivity {
private ListView PatientLocationListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.PatientLocationListView = (ListView) this.findViewById(R.id.listView4);
new Location().execute(new API_Connector());
}
public void setListAdapter(JSONArray jsonArray) {
SharedPreferences settings = getSharedPreferences("myprefrences", Context.MODE_PRIVATE);
String name = settings.getString("name", "");
this.PatientLocationListView.setAdapter(new PatientAdapter(jsonArray,name, this));
}
private class Location extends AsyncTask<API_Connector, Long, JSONArray> {
#Override
protected JSONArray doInBackground(API_Connector... params) {
//it is executed on Background thread
return params[0].GetPatientLocation();
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
// check for null
if (jsonArray != null) {
// only pass the array to adapter if it is not null
setListAdapter(jsonArray);
} else {
Toast.makeText(PatientLocation.this, "Null Array returned", Toast.LENGTH_SHORT).show();
}
}
}
}
class PatientAdapter extends BaseAdapter {
private JSONArray dataArray;
private Activity activity;
String pname;
private static LayoutInflater inflater = null;
public PatientAdapter(JSONArray jsonArray, String name, Activity a) {
this.dataArray = jsonArray;
this.activity = a;
this.pname = name;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.dataArray.length();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String patientname,patientlocation;
//set up convert view if it is null
ListCell cell = new ListCell();
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_position, null);
cell.patient_name = (TextView) convertView.findViewById(R.id.textView30);
cell.patient_location = (TextView) convertView.findViewById(R.id.textView31);
convertView.setTag(cell);
}
else {
cell = (ListCell) convertView.getTag();
}
//change the data of the cell
try {
for(int i=0;i<dataArray.length();i++) {
JSONObject jsonObject = this.dataArray.getJSONObject(i);
if(pname == jsonObject.getString("Name")) {
patientname = jsonObject.getString("Name");
patientlocation = jsonObject.getString("Location");
cell.patient_name.setText(patientname);
cell.patient_location.setText(patientlocation);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private class ListCell {
private TextView patient_name;
private TextView patient_location;
}
}
Where is WHERE clause in your query in php code? You need to set some conditions to match specific name in query like if you want to search 'abcd' then your query should be SELECT * FROM groupdesign WHERE column_name = "abcd". This will return records which contanis value "abcd" from your database
Related
I try to get data from the database via API but the recyclerview doesn't display anything and the log displays an error.
This is my code
Fragment
package com.example.hp.retailmakanan;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
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 com.example.hp.retailmakanan.Model.MenuModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FragHome extends Fragment {
RecyclerView recV;
BottomNavigationView top_navigation;
HomeAdapter listAdapter;
List<MenuModel> listMenu= new ArrayList<>();
private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment sfragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_noodle:
recV.setAdapter(listAdapter);
break;
case R.id.nav_beverage:
recV.setAdapter(listAdapter);
break;
case R.id.nav_toping:
recV.setAdapter(listAdapter);
break;
case R.id.nav_cari:
recV.setAdapter(listAdapter);
break;
}
return false;
}
};
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.act_home, container, false);
recV = (RecyclerView) v.findViewById(R.id.rec_ramen);
getData();
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recV.setLayoutManager(layoutManager);
listAdapter = new HomeAdapter(listMenu, getActivity());
recV.setAdapter(listAdapter);
top_navigation = (BottomNavigationView) v.findViewById(R.id.top_nav);
top_navigation.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
return v;
}
this is the code that i used to get data
private void getData() {
String url ="https://waggish-requisition.000webhostapp.com/GetAllMenu.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listMenu.clear();
for (int i = 0; i < response.length(); i++) {
try {
Log.d("menu",response.toString());
JSONObject jsonObject = response.getJSONObject(i);
String id_menu = jsonObject.getString("id");
String nama_menu = jsonObject.getString("nama_menu");
String deskripsi = jsonObject.getString("deskripsi");
int harga = jsonObject.getInt("harga");
MenuModel menus = new MenuModel(id_menu,nama_menu,deskripsi,harga);
listMenu.add(menus);
System.out.println(menus);
//Toast.makeText(this,"Download data "+i,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Log.d("menu",e.toString());
}
listAdapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
}
Adapter
package com.example.hp.retailmakanan;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.hp.retailmakanan.Model.MenuModel;
import java.util.Arrays;
import java.util.List;
public class HomeAdapter extends RecyclerView.Adapter {
private List<MenuModel> menus;
private Context context;
public HomeAdapter(List<MenuModel> menus, Context context) {
this.context = context;
this.menus = menus;
//System.out.println(menus);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recv_desain, viewGroup, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int pos) {
}
#Override
public int getItemCount() {
return menus.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mText,txt2, txt3, txtQty;
ImageView img;
Button btnMin, btnPlus;
int x;
public ListViewHolder(View itemView){
super(itemView);
mText = itemView.findViewById(R.id.text_item);
txt2 = itemView.findViewById(R.id.text_item2);
txt3 = itemView.findViewById(R.id.textView3);
img = itemView.findViewById(R.id.image_item);
btnMin = itemView.findViewById(R.id.buttonMinMenu);
btnPlus = itemView.findViewById(R.id.buttonPlusMenu);
txtQty = itemView.findViewById(R.id.textQtyMenu);
itemView.setOnClickListener(this);
}
public void bindView (int pos){
x=0;
MenuModel model = menus.get(pos);
mText.setText(model.getNama_menu());
txt2.setText(model.getDeskripsi());
txt3.setText(model.getHarga());
//img.setImageResource(DataMenu.picture[pos]);
txtQty.setText(String.valueOf(x));
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
txtQty.setText(String.valueOf(x));
}
});
btnMin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x--;
if (x<=0){
x=0;
txtQty.setText(String.valueOf(x));
}else if (x>0){
txtQty.setText(String.valueOf(x));
}
}
});
}
#Override
public void onClick(View v) {
}
}
}
And this is my php code
<?php
require_once('connection.php');
//public $mServerName;
//public $mConnectionInfo;
//public $conn;
//Create query to retrieve all contacts
$query = "SELECT * FROM menu";
$stmt = mysqli_query($conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$menus= array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = mysqli_fetch_array($stmt)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$menu= array("id" => $row['id_menu'],
"deskripsi" => $row['Deskripsi'],
"nama_menu" => $row['nm_menu'],
"harga" => $row['harga_menu'],
"ImageUrl" =>$row['gambar']
);
//Add the contact to the contacts array
array_push($menus, $menu);
}
//Echo out the contacts array in JSON format
echo json_encode($menus);
}
?>
I changed JSONObject to JSONArray, but that caused many other errors. I am a beginner please help me. I really don't know what to do :(
I have a custom listview adapter setup up that I need to call in my fragment, but I can't seem the pass my activity to it. I have a very similar set up, but called from within an activity, and it works very well. So, I think the issue is with passing the activity context to the adapter, but I'm not sure how to achieve it.
Below is the code for my fragment, where I make the call to my custom adapter:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class SiblingUnitFragment extends Fragment {
Context siblingContext = this.getActivity();
Activity context = this.getActivity();
ProgressDialog progressDialog;
ListView siblingLVAdapter;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultSiblings;
String HttpURLSiblings = "https://[myDataSpot]/getSiblings.php";
HashMap<String, String> hashMapSiblings = new HashMap<>();
HttpParse httpParse = new HttpParse();
String[] Uuid;
String[] Usize;
String[] Ustatus;
String SV;
String[] svSeparated;
ListView siblingListView;
public SiblingUnitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_siblings, container, false);
siblingListView = (ListView) view.findViewById(R.id.SiblingsList);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getArguments() != null) {
SV = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
}
if (SV.contains("-")) {
svSeparated = SV.split("-");
SearchValue = svSeparated[0];
getSiblings(SearchValue, LexaUser);
} else {
SearchValue = SV;
getSiblings(SearchValue, LexaUser);
}
}
public void getSiblings(String searchInput, String lexaUser) {
class SiblingsClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(siblingContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONArray json = new JSONArray(httpResponseMsg);
Uuid = new String[json.length()];
Usize = new String[json.length()];
Ustatus = new String[json.length()];
for (int i = 0; i < json.length(); i++) {
JSONObject object = json.getJSONObject(i);
Uuid[i] = object.getString("id");
Usize[i] = object.getString("size");
Ustatus[i] = object.getString("status");
}
siblingLVAdapter = new SiblingsListViewAdapter(context, Uuid, Usize, Ustatus);
siblingListView.setAdapter(siblingLVAdapter);
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(siblingContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(siblingContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapSiblings.put("searchinput", params[0]);
hashMapSiblings.put("lexauser", params[1]);
finalResultSiblings = httpParse.postRequest(hashMapSiblings, HttpURLSiblings);
return finalResultSiblings;
}
}
SiblingsClass siblingsClass = new SiblingsClass();
siblingsClass.execute(searchInput, lexaUser);
}
}
And this is my code for the adapter:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SiblingsListViewAdapter extends BaseAdapter {
Activity context;
String Uuid[];
String Usize[];
String Ustatus[];
public SiblingsListViewAdapter(Activity context, String[] Uuid, String[] Usize, String[] Ustatus) {
super();
this.context = context;
this.Uuid = Uuid;
this.Usize = Usize;
this.Ustatus = Ustatus;
}
public int getCount() {
// TODO Auto-generated method stub
return Uuid.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewUid;
TextView txtViewSize;
TextView txtViewStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.siblings_list, null);
holder = new ViewHolder();
holder.txtViewUid = (TextView) convertView.findViewById(R.id.SiblingsUid);
holder.txtViewSize = (TextView) convertView.findViewById(R.id.SiblingsSize);
holder.txtViewStatus = (TextView) convertView.findViewById(R.id.SiblingsStatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewUid.setText(Uuid[position]);
holder.txtViewSize.setText(Usize[position]);
holder.txtViewStatus.setText(Ustatus[position]);
return convertView;
}
}
And here is the logcat error:
error: incompatible types: SiblingsListViewAdapter cannot be converted to ListView
All help is appreciated. Thank you!
A per the Fragment Lifecycle, You need to call getContext only after onAttach method of your fragment lifecycle is called otherwise there is no associated activity hence there is no context
so use it like
// declare context
Context siblingContext ;
then initialise it
.. onCreateView(...){
siblingContext = getContext();
context = getActvity();
}
you mistake in instantiate your adapter in line 24.change ListView siblingLVAdapter; to
SiblingsListViewAdapter siblingLVAdapter;
and use Context context =getActivity(); or Activity activity=getActivity(); in onAtach methode
I am new to android. I am trying to download data using the Github api and display in and infinite scrolling RecyclerView, the JSON data is been parsed, but somehow the data is not been attached to the recyclerview.
Here is the code below:
Developer_RV_Adapter.java
package com.davidshare.githubdevelopers;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by GemShare on 9/6/2017.
*/
public class Developer_RV_Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 10;
private int lastVisibleItem, totalItemCount;
private List<Developer> developerList;
Context context;
RecyclerView recyclerView;
public Developer_RV_Adapter(Context context, List<Developer> developerList, RecyclerView recyclerView) {
this.developerList = developerList;
this.context = context;
this.recyclerView = recyclerView;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if(!isLoading && totalItemCount<=(lastVisibleItem+visibleThreshold)){
if(mOnLoadMoreListener!=null){
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setmOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener){
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position){
return developerList.get(position) == null? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_ITEM){
View developerView = LayoutInflater.from(context).inflate(R.layout.developer_list_item, parent, false);
return new DeveloperViewHolder(developerView);
}else if(viewType== VIEW_TYPE_LOADING){
View loadingView = LayoutInflater.from(context).inflate(R.layout.progress_bar_item, parent, false);
return new ProgressViewHolder(loadingView);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Log.w("binder function", "Just entered the binder");
Developer developer = developerList.get(position);
if(holder instanceof DeveloperViewHolder){
DeveloperViewHolder developerViewHolder = (DeveloperViewHolder) holder;
developerViewHolder.gitNameTv.setText(developer.getGitUsername());
Log.w("binder ", developer.getGitProfileUrl());
developerViewHolder.gitUrlTv.setText(developer.getGitProfileUrl());
developerViewHolder.gitPicUrlTv.setText(developer.getGitProfilePicUrl());
Log.w("profile pic", developer.getGitProfilePicUrl());
Picasso.with(developerViewHolder.gitNameTv.getContext()).load(developer.getGitProfilePicUrl()).transform(new RoundedImage(2)).fit().centerCrop().into(developerViewHolder.profilePicImgV);
}else if (holder instanceof ProgressViewHolder) {
ProgressViewHolder loadingViewHolder = (ProgressViewHolder) holder;
loadingViewHolder.loadingProgress.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return developerList == null ? 0 : developerList.size();
}
public void setLoaded() {
isLoading = false;
}
public class DeveloperViewHolder extends RecyclerView.ViewHolder{
TextView gitNameTv;
TextView gitUrlTv;
ImageView profilePicImgV;
TextView gitPicUrlTv;
public DeveloperViewHolder(final View itemView) {
super(itemView);
gitNameTv = (TextView) itemView.findViewById(R.id.developerName);
gitUrlTv = (TextView) itemView.findViewById(R.id.developerUrl);
profilePicImgV = (ImageView) itemView.findViewById(R.id.developerPic);
gitPicUrlTv = (TextView) itemView.findViewById(R.id.developerPicUrl);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(itemView.getContext(), Profile.class);
i.putExtra("profile_name", gitNameTv.getText().toString());
i.putExtra("profile_url", gitUrlTv.getText().toString());
i.putExtra("profile_pic_url", gitPicUrlTv.getText().toString());
v.getContext().startActivity(i);
}
});
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder{
public ProgressBar loadingProgress;
public ProgressViewHolder(View itemView) {
super(itemView);
loadingProgress = (ProgressBar) itemView.findViewById(R.id.loading_progress_bar);
}
}
}
DeveloperList.java
package com.davidshare.githubdevelopers;
import android.app.ProgressDialog;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DeveloperList extends AppCompatActivity {
List<Developer> developerList;
Developer_RV_Adapter developer_rv_adapter;
Developer developer;
RecyclerView developerRV;
private static final String GIT_BASE_URL = "https://api.github.com/search/users?q=location:";
private static int page = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_developer_list);
developerRV = (RecyclerView) findViewById(R.id.developer_rv);
developerRV.setLayoutManager(new LinearLayoutManager(this));
developerList = new ArrayList<>();
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter = new Developer_RV_Adapter(DeveloperList.this, developerList, developerRV);
developerRV.setAdapter(developer_rv_adapter);
developer_rv_adapter.setmOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
developerList.add(null);
developer_rv_adapter.notifyItemInserted(developerList.size()-1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
developerList.remove(developerList.size()-1);
developer_rv_adapter.notifyItemRemoved(developerList.size());
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter.notifyDataSetChanged();
developer_rv_adapter.setLoaded();
}
}, 5000);
}
});
}
the getDevelopersData method uses volley to query the github api and parse the JSON response into a List
public void getDevelopersData(String requestUrl) {
StringRequest jsonSringRequest = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String jsonResponse) {
try {
JSONObject gitJSONOBject = new JSONObject(jsonResponse);
JSONArray gitItemsArray = gitJSONOBject.getJSONArray("items");
for (int i = 0; i < gitItemsArray.length(); i++) {
JSONObject developerObject = gitItemsArray.getJSONObject(i);
developer = new Developer(developerObject.getString("login"),
developerObject.getString("html_url"),
developerObject.getString("avatar_url"));
developerList.add(developer);
Log.w("developer_data ", developer.getGitUsername());
}
Log.w("JSON DATA", "getting the json data");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Volley error", volleyError.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonSringRequest);
}
//get the location and language and the page of the api data you want to load
private String prepareQuery(String language, String location, int page){
this.page++;
String queryUrl = GIT_BASE_URL+location+"+language:"+language+"&page="+page+"&per_page=50";
Log.w("Query URL = > ", queryUrl);
return queryUrl;
}
}
Can anyone help me with this?
try to notify adapter in getDevelopersData() after data add to array list like add this line developer_rv_adapter.notifyDataSetChanged();
Instead of notifyItemInserted() inserted use
notifyItemRangedChanged(fromIndex,toIndex);
This will notify the adapter that some set of data is changed among the whole data and it tells the adapter that adapter should refresh the data and reload it into the recyclerView starting from fromIndex to toIndex as passed into the method.
If all data are changed then use :
notifyDataSetChanged();
if only one dataItem is changed then use :
notifyItemChanged(dataPosition);
Also I think this statment is causing problem.Try to remove this statment and check again.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
developerList.remove(developerList.size()-1);
developer_rv_adapter.notifyItemRemoved(developerList.size());
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter.notifyDataSetChanged();
developer_rv_adapter.setLoaded();
}
}, 5000);
The problem was resolved by just adding developer_rv_adapter.notifyDataSetChanged(); just below developerList.add(developer); this notifies the adapter that new items have been added to the list.
When i tap search donor then it shows blank screen in listview i don't know why This is the response that i get back from server
This is my custom adapter code:
package com.example.kamran.ebloodbank;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Kamran on 4/12/2017.
*/
public class DonorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataSet> donorItems;
public DonorAdapter(Activity activity,List<DataSet> donorItems) {
this.activity = activity;
this.donorItems = donorItems;
}
#Override
public int getCount() {
return donorItems.size();
}
#Override
public Object getItem(int location) {
return donorItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.donor_search_list_theme, null);
TextView nameTextView = (TextView) convertView.findViewById(R.id.donor_name);
TextView areaTextView = (TextView) convertView.findViewById(R.id.donor_area);
DataSet d = donorItems.get(position);
nameTextView.setText(d.getName());
areaTextView.setText(d.getArea());
return convertView;
}
}
This is my model code:
package com.example.kamran.ebloodbank;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
/**
* Created by Kamran on 4/12/2017.
*/
public class DataSet {
private String name;
private int area;
public void setArea(int area) {
this.area = area;
}
public void setName(String name) {
this.name = name;
}
public int getArea() {
return area;
}
public String getName() {
return name;
}
}
This is my first activity code:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.kamran.ebloodbank.data.BloodContract.BloodEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindDonor extends AppCompatActivity {
Spinner bloodgroup;
Spinner area;
String findDonorUrl = "https://wwwkamranalitk.000webhostapp.com/findDonor.php";
int mBlood = BloodEntry.BLOOD_GROUP_A_POS;
int mArea = BloodEntry.DONOR_AREA_MALIR;
Button searchButton;
RequestQueue requestQueue;
StringRequest request;
JSONObject jsonObject;
JSONArray result;
private List<DataSet> donorList = new ArrayList<DataSet>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_donor);
bloodgroup = (Spinner) findViewById(R.id.bloodspinnerfinddonor);
area = (Spinner) findViewById(R.id.areaSpinner);
searchButton = (Button) findViewById(R.id.searchDonor);
setupSpinnerBlood();
setupSpinnerArea();
requestQueue = Volley.newRequestQueue(getApplicationContext());
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, findDonorUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObject = new JSONObject(response);
result = jsonObject.getJSONArray("result");
JSONObject donorData = result.getJSONObject(0);
DataSet donorSet = new DataSet();
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("bloodgroup", String.valueOf(mBlood));
parameters.put("area", String.valueOf(mArea));
return parameters;
}
};
requestQueue.add(request);
}
});
}
private void setupSpinnerBlood() {
ArrayAdapter bloodGroupSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.blood_group, android.R.layout.simple_spinner_item);
bloodGroupSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
bloodgroup.setAdapter(bloodGroupSpinnerAdapter);
bloodgroup.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blood_apos))) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
} else if (selection.equals((getString(R.string.blood_bpos)))) {
mBlood = BloodEntry.BLOOD_GROUP_B_POS;
} else if (selection.equals(getString(R.string.blood_opos))) {
mBlood = BloodEntry.BLOOD_GROUP_O_POS;
} else if (selection.equals((getString(R.string.blood_oneg)))) {
mBlood = BloodEntry.BLOOD_GROUP_O_NEG;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
}
});
}
private void setupSpinnerArea() {
ArrayAdapter areaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.area, android.R.layout.simple_spinner_item);
areaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
area.setAdapter(areaSpinnerAdapter);
area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.donor_area_malir))) {
mArea = BloodEntry.DONOR_AREA_MALIR;
} else if (selection.equals(getString(R.string.donor_area_defence))) {
mArea = BloodEntry.DONOR_AREA_DEFENCE;
} else if (selection.equals(getString(R.string.donor_area_korangi))) {
mArea = BloodEntry.DONOR_AREA_KORANGI;
} else if (selection.equals(getString(R.string.donor_area_johar))) {
mArea = BloodEntry.DONOR_AREA_JOHAR;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mArea = BloodEntry.DONOR_AREA_MALIR;
}
});
}
}
and This is the code in which data will be shown:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DonorSearchList extends AppCompatActivity {
private String mArea;
private List<DataSet> donorList = new ArrayList<DataSet>();
private ListView listView;
private DonorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donor_search_list);
listView = (ListView) findViewById(R.id.donorListView);
adapter = new DonorAdapter(this, donorList);
listView.setAdapter(adapter);
}
}
You need to transfer data from the search to list activity.
Try something like this:
public class bridge {
public static List<DataSet> donorList = new ArrayList<DataSet>();
}
Then, in the class FindDonor:
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
//here put this line
bridge.donarList = donarList;
//rest code
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
Then, in the DonorSearchList class:
adapter = new DonorAdapter(this, bridge.donorList);
Ok the app populates the list view from a Url(json). But I want to change the app so that the list view is populated by user input. How do I go about this. Here is my main activity so far:
package ionictech.com.onspot;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import ionictech.com.onspot.adapter.FeedListAdapter;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;
public class OnSpotActivity extends ActionBarActivity {
private DrawerLayout drawerLayout;
private String[] Menu;
private static final String TAG = OnSpotActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_spot);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem> ();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable (Color.parseColor ("#ffba00")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getmInstance ().getmRequestQueue ().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d (TAG, "Response: " + response.toString ());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getmInstance ().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And here is my feed item list class:
package ionictech.com.onspot.adapter;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import ionictech.com.onspot.FeedImageView;
import ionictech.com.onspot.R;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;
/**
* Created by MarcusLee on 9/30/14.
*/
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getmInstance ().getImageLoader();
public FeedListAdapter (Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getmInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString (
Long.parseLong (item.getTimeStamp ()),
System.currentTimeMillis (), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty (item.getStatus ())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml ("<a href=\"" + item.getUrl () + "\">"
+ item.getUrl () + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance ());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
I know that the input has to be sent to a server and then read and put into the list view, I just don't know the methods and such. Any help would be most grateful!