I'm just doing some learning and can't see why this ArrayList is initialised but can't be used outside of method its populated within. Can anyone explain? Thanks in advance...
For example if I aske the ArrayList.size() within the method it shows that it has been initialised but elsewhere outside the method it won't.
package com.purewowstudio.animations;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
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.google.gson.GsonBuilder;
import com.purewowstudio.animations.extras.CustomGrid;
import com.purewowstudio.animations.models.ActorArray;
import com.purewowstudio.animations.models.ActorObject;
import java.util.ArrayList;
public class ActorList extends ActionBarActivity {
String LOG_TAG = ActorList.class.getSimpleName();
private ArrayList<ActorObject> actorObjectArrayList;
ActorArray actorArray;
GridView actorGrid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actors_list);
getActors();
if (actorObjectArrayList != null) {
ActorObject[] actors = actorObjectArrayList.toArray(new ActorObject[actorObjectArrayList.size()]);
String actorsNames[] = new String[actorObjectArrayList.size()];
String actorsImages[] = new String[actorObjectArrayList.size()];
for (int i = 0; i < actorObjectArrayList.size(); i++) {
actorsNames[i] = actors[i].getName();
actorsImages[i] = actors[i].getImage();
}
CustomGrid adapter = new CustomGrid(ActorList.this, actorsNames, actorsImages);
actorGrid = (GridView) findViewById(R.id.grid);
actorGrid.setAdapter(adapter);
actorGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(ActorList.this, "You Clicked at " + actorsNames[+position], Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.animation_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getActors(){
String url ="http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
actorArray = new GsonBuilder().create().fromJson(response, ActorArray.class);
actorObjectArrayList = actorArray.getActors();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.v(LOG_TAG, "Volley Error");
}
});
queue.add(stringRequest);
}
}
The reason why you can't access the content with which you initialized the arraylist in other methods is simple. It is local data inside the scope of the OnCreate. You should define a constructor of your class and initialize the arraylist there. Then in your methods, you can add the data that you need to add. When you'll be looking for data within the arraylist, it will have everything that you're looking for.
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 :(
package com.example.murarilal.volley;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
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.JsonObjectRequest;
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.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
ListView listView;
List<Hero> heroList;
private String url="API_KEY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(this);
home();
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
intent.putExtra("description",url);
startActivity(intent);
}
});
}
public void home()
{
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(String.valueOf(response));
JSONArray array = obj.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
package com.example.murarilal.volley;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ArticleActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";
WebView webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
Intent intent=getIntent();
webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
webView.loadUrl(url);
}
}
https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e
I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity
this the log error
11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
14350-14350/com.example.murarilal.volley W/System.err: at
com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
W/System.err: at
com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
ListView listView;
List<Hero> heroList;
private String url="https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(this);
home();
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
/* Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
intent.putExtra("description",url);
startActivity(intent);*/
}
});
}
public void home()
{
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(String.valueOf(response));
JSONArray array = obj.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
Log.d("title ", String.valueOf(array.getJSONObject(i).get("title")));
Log.d("urlToImage ", String.valueOf(array.getJSONObject(i).get("urlToImage")));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
Try to use URLConnection instead of volley.
401 indicates of have Unauthorized access to the given URL
I tried both api V1 And V2 with volley and got status code 200 and the data matches with the data shown when the request is made from a browser.
To help Can you add Logs and post it over here
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,error.networkResponse.toString());
error.printStackTrace();
}
});
Have you tried adding this line in your gradle file.
I've implemented your code, the data is being called properly.
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
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);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm a newbie coding witch android studio and I try to save data on editText inside a recyclerview but data disappear or is duplicated in another editText.
Could someone help me please ?
Here is my code :
TaskActivity.java
package com.example.davidsimon.appexploit.activities;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.opengl.EGLDisplay;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.davidsimon.appexploit.R;
import com.example.davidsimon.appexploit.classes.ReturnResponse;
import com.example.davidsimon.appexploit.classes.Task;
import com.example.davidsimon.appexploit.classes.TaskAdapter;
import com.example.davidsimon.appexploit.classes.TaskToSend;
import com.example.davidsimon.appexploit.classes.User;
import com.example.davidsimon.appexploit.services.JsonService;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static android.R.attr.button;
import static android.R.attr.title;
public class TasksActivity extends AppCompatActivity {
private List<Task> taskList = new ArrayList<>();
private RecyclerView recyclerView;
public TaskAdapter mAdapter;
Button GoPhoto;
String user;
JsonService service;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
Button uploadButton = (Button) findViewById(R.id.butUpload);
GoPhoto = (Button) findViewById(R.id.butt_photo);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getString(R.string.base_url))
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(JsonService.class);
Button takePictureButton = (Button) findViewById(R.id.butt_photo);
user = getIntent().getStringExtra("user");
//imageView = (ImageView) findViewById(R.id.imageview);
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TaskToSend task;
List<TaskToSend> listTask = new ArrayList<>();
for (int i = 0; i < mAdapter.getItemCount(); i++) {
task = new TaskToSend(mAdapter.getItem(i).getTitle(), String.valueOf(mAdapter.getItem(i).isState()), mAdapter.getItem(i).getComment(), user);
if (task.getState() == "true") {
task.setState("Fait");
} else {
task.setState("Non fait");
}
listTask.add(task);
}
service.saveTasks(listTask).enqueue(new Callback<ReturnResponse>() {
#Override
public void onResponse(Call<ReturnResponse> call, Response<ReturnResponse> response) {
Log.wtf("Fichier", "RĂ©ponse");
}
#Override
public void onFailure(Call<ReturnResponse> call, Throwable t) {
Log.wtf("Fichier", "Pas de réponse");
}
});
Intent TakstoUpload = new Intent(TasksActivity.this, UploadActivity.class);
startActivity(TakstoUpload);
}
});
takePictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
service.getTasks().enqueue(new Callback<List<Task>>() {
#Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
List<Task> listeTaches = response.body();
Log.wtf("Nombre de taches", "Nombre de taches : " + listeTaches.size());
Calendar c = Calendar.getInstance();
int DayOfWeek = c.get(Calendar.DAY_OF_WEEK);
for (Task t : listeTaches) {
if (t.getPeriod()== DayOfWeek || t.getPeriod()== 0) {
taskList.add(t);
}
}
displayRecyclerView();
}
#Override
public void onFailure(Call<List<Task>> call, Throwable t) {
Log.wtf("GetTasks Failure", t.toString());
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void displayRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.tasks_recycler_view);
mAdapter = new TaskAdapter(taskList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Tasks Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Here my adapter TaskAdapter :
package com.example.davidsimon.appexploit.classes;
import android.content.Context;
import android.graphics.Movie;
import android.support.v7.widget.ListViewCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import com.example.davidsimon.appexploit.R;
import com.example.davidsimon.appexploit.activities.TasksActivity;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.data;
import static android.R.attr.value;
import static com.example.davidsimon.appexploit.R.id.checkBox;
/**
* Created by David SIMON on 22/08/2016.
*/
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.MyViewHolder> {
private List<Task> TaskList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public CheckBox checkBox;
public EditText finalComment;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
checkBox = (CheckBox) view.findViewById(R.id.checkBox);
finalComment = (EditText) view.findViewById(R.id.FinalComment);
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
int position = (int) finalComment.getTag();
TaskList.get(position).setComment(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
};
finalComment.addTextChangedListener(textWatcher);
}
}
public TaskAdapter(List<Task> TaskList) {
this.TaskList = TaskList;
}
#Override
public TaskAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyvlerview, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Task task = TaskList.get(position);
holder.title.setText(task.getTitle());
holder.finalComment.setTag(position);
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(task.isState());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
task.setState(b);
}
});
}
public Task getItem(int position){
return TaskList.get(position);
}
#Override
public int getItemCount() {
return TaskList.size();
}
}
And my Task.java
package com.example.davidsimon.appexploit.classes;
/**
* Created by David SIMON on 05/08/2016.
*/
public class Task {
String title;
boolean state;
String comment;
int period;
String type;
public Task(String title, boolean state, String comment, String type, int period) {
this.title = title;
this.state = state;
this.comment = comment;
this.type = type;
this.period = period;
}
#Override
public String toString() {
return "Title : "+ title +
"\nState : " + state +
"\nComment : " + comment +
"\nPeriod : " + period +
"\nType : " + type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setState(boolean state) {
this.state = state;
}
public boolean isState() {
return state;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getPeriod() { return period; }
public void setPeriod(int period) { this.period = period; }
}
I just want to save data in my EditText "finalcomment". I already search some similar problem but I think my level is too low.
Thanks in advance
A RecyclerView will reuse your views. So whenever you scroll onBindViewHolder will be called. Within that method you need to setup the view with the correct data. You need to set the EditText in your onBindViewHolder which will likely require you to save the tex that has been entered. Here's an example of how you'd do that without the save logic:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Task task = TaskList.get(position);
holder.title.setText(task.getTitle());
holder.finalComment.setTag(position);
// You need to save the entered text and then set it in onBindViewHolder
holder.finalComment.setText(THE TEXT FOR THE EDIT TEXT);
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(task.isState());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
task.setState(b);
}
});
}
I think you have a problem in recycling views.
Your RecyclerView reuse views that exited from the screen for other object, to save time and memory.
So what you need is to always set all desired data into onBindViewHolder method. Otherwise if a view exit from the visible screen and it is reused, it will be reused with old data.
Using EditText into RecyclerView is not a good decision, because you are mixing user inputs with presentation data.
If you want to keep this approach, you must find a way to save data associated to each RecyclerView item, to be then always able to set them to the right recycled view when it becomes again visible.
Obviously you need also to keep information of empty views.
Hope I have clarified enough
I seen a problem, if my solution doesn't work then let me know!
Inside your TaskAdapter class, onBindViewHolder() method:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Task task = TaskList.get(position);
holder.title.setText(task.getTitle());
//this one is wrong
//holder.finalComment.setTag(position);
//while doing this you will get the text of final comment in your
//edit text of final comment
holder.finalComment.setText(task.getComment());
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(task.isState());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
task.setState(b);
}
});
}
I'm trying to populate a recycle adapter from a controller class, to split the logic in the app. But I can't seem to get it working.. Do to the request is running on another thread, the view is not updated before it is shown. What am I doing wrong ?
FragmentClass:
package lassebjoerklund.homecontrol.views.fragments;
import android.app.Fragment;
import android.os.Bundle;
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 com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.controllers.FridgeController;
import lassebjoerklund.homecontrol.decorations.DividerItemDecoration;
import lassebjoerklund.homecontrol.model.Product;
import lassebjoerklund.homecontrol.utils.FragmentUtil;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverView extends Fragment {
private final FridgeController fridgeController = new FridgeController();
private RecyclerView recyclerView;
private LinkedList<String> types;
private FridgeFragmentOverViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_layout, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productOverviewRecycleView);
recyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new FridgeFragmentOverViewAdapter(fridgeController.getProductsTypes());
recyclerView.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
fridgeController.refresh(getContext(), adapter);
}
}
Controller Class:
package lassebjoerklund.homecontrol.controllers;
import android.content.Context;
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;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.interfaces.OnSucsess;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeController implements OnSucsess {
private RequestQueue rQueue;
private ArrayList<Product> products;
private List<String> productsTypes;
public ArrayList<Product> getProducts() {
return products;
}
public List<String> getProductsTypes() {
return productsTypes;
}
public void refresh(Context context, final FridgeFragmentOverViewAdapter adapter) {
String fetchProducts = "http://87.52.28.25:900/index.php";
rQueue = Volley.newRequestQueue(context);
final JsonArrayRequest getProductsRequest = new JsonArrayRequest(fetchProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
products = new ArrayList<>();
productsTypes = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) response.get(i);
String barcode = jsonObject.getString("code");
String name = jsonObject.getString("name");
String ex_date = jsonObject.getString("ex_date");
String add_date = jsonObject.getString("add_date");
String type = jsonObject.getString("type");
Product product = new Product(barcode, name, ex_date, add_date, type);
products.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (products.size() != 0) {
for (int i = 0; i < products.size(); i++) {
if (!productsTypes.contains(products.get(i).getType())) {
productsTypes.add(products.get(i).getType());
}
}
}
getProductsOnsucsess(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQueue.add(getProductsRequest);
}
#Override
public void getProductsOnsucsess(FridgeFragmentOverViewAdapter adapter) {
adapter.refreshAdapter(productsTypes);
}
}
Adapter:
package lassebjoerklund.homecontrol.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverViewAdapter extends RecyclerView.Adapter {
private List<String> types;
public FridgeFragmentOverViewAdapter(List<String> types) {
this.types = types;
}
#Override
public int getItemCount() {
return 0;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_overview_card_layout, null);
return new ProductsGroupedHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
public class ProductsGroupedHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTypeOfProduct, tvCount, tvExpired;
public ProductsGroupedHolder(View itemView) {
super(itemView);
tvTypeOfProduct = (TextView) itemView.findViewById(R.id.tvTypeOfProduct);
tvCount = (TextView) itemView.findViewById(R.id.tvCount);
tvExpired = (TextView) itemView.findViewById(R.id.tvExpired);
}
#Override
public void onClick(View v) {
}
}
public void refreshAdapter(List<String> types) {
if(this.types != null) {
this.types.clear();
this.types = types;
notifyDataSetChanged();
}else {
this.types = types;
notifyDataSetChanged();
}
}
}
Try calling:
adapter.notifyDataSetChanged();
after updating it.
Edit 1:
Return actual size of adapter items in getItemCount() as #prathamkesarkar said.
Simple looks like you have set the getItemType() method return 0.
That method determines how much item your RecyclerView have.
#Override
public int getItemCount() {
return type.size();
}