My ListView is not refreshing after i am using notifyDataSetChanged();
but i dont know what is wrong in my code please help me how to update my listview when my database is update.
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class EventsView extends Fragment {
ListView list4;
String json_string;
String JSON_STRING;
JSONObject JO;
JSONObject jsonObject;
JSONArray jsonArray;
int count = 0;
HashMap<String, Object> obj;
String topic,description,event_date,event_id;
private Context mContext;
private PopupWindow mPopupWindow;
private LinearLayout linearLayout;
private Activity mActivity;
ProgressDialog pDialog;
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
HttpParse httpParse = new HttpParse();
String HttpURL = "http://192.168.1.10:8081/sms/update_event.php";
String HttpURLDelete = "http://192.168.1.10:8081/sms/delete_event.php";
SimpleAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.events_view, container, false);
mContext = getContext();
mActivity = getActivity();
linearLayout = (LinearLayout) view.findViewById(R.id.r2);
list4=(ListView)view.findViewById(R.id.list4);
new show_event().execute();
list4.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
obj = (HashMap<String, Object>) list4.getAdapter().getItem(position);
new show_list().execute();
}
});
return view;
}
class show_event extends AsyncTask<String,String,String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://192.168.1.10:8081/sms/select_event.php";
pdLoading.setMessage("\tLoading...");
pdLoading.isIndeterminate();
pdLoading.setIndeterminate(true);
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()).equals("null")) ;
{
stringBuilder.append(JSON_STRING +"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
List<Map<String, String>> data2 = null;
data2 = new ArrayList<Map<String, String>>();
json_string = result;
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
if (jsonArray.length() != 0) {
for (count = 0; count < jsonArray.length(); count++) {
JO = jsonArray.getJSONObject(count);
HashMap<String, String> datanum = new HashMap<String, String>();
datanum.put("A",JO.getString("Id"));
datanum.put("B",JO.getString("Topic"));
datanum.put("C",JO.getString("Description"));
datanum.put("D",JO.getString("Event_Date"));
data2.add(datanum);
}
adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
list4.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
pdLoading.dismiss();
}
}
class show_list extends AsyncTask<String,String,String> {
private int mYear, mMonth, mDay;
ProgressDialog pdLoading = new ProgressDialog(getActivity());
#Override
protected String doInBackground(String... strings) {
event_id=(String)obj.get("A");
topic = (String) obj.get("B");
description=(String)obj.get("C");
event_date=(String)obj.get("D");
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.isIndeterminate();
pdLoading.setIndeterminate(true);
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
final View customView = inflater.inflate(R.layout.edit_event,null);
mPopupWindow = new PopupWindow(customView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
mPopupWindow.setOutsideTouchable(true);
if(Build.VERSION.SDK_INT>=21){
mPopupWindow.setElevation(5.0f);
}
final EditText edit_topic=(EditText)customView.findViewById(R.id.edit_topic);
final EditText edit_description=(EditText)customView.findViewById(R.id.edit_description);
final EditText edit_date=(EditText)customView.findViewById(R.id.edit_Date);
Button delete_btn=(Button)customView.findViewById(R.id.delete);
Button update_btn=(Button)customView.findViewById(R.id.update);
edit_topic.setText(topic);
edit_description.setText(description);
edit_date.setText(event_date);
final String id=String.valueOf(event_id);
edit_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
edit_date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String topic= edit_topic.getText().toString();
String description= edit_description.getText().toString();
String edit_event_date=edit_date.getText().toString();
StudentRecordUpdate(id,topic,description,edit_event_date);
mPopupWindow.dismiss();
}
});
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StudentDelete(id);
}
});
mPopupWindow.showAtLocation(linearLayout, Gravity.CENTER,0,0);
mPopupWindow.setFocusable(true);
mPopupWindow.update();
pdLoading.dismiss();
}
}
public void StudentRecordUpdate(final String id, final String topic, final String description, final String event_date){
class StudentRecordUpdateClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
Toast.makeText(getActivity(),httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
hashMap.put("Id",params[0]);
hashMap.put("Topic",params[1]);
hashMap.put("Description",params[2]);
hashMap.put("Event_Date",params[3]);
finalResult = httpParse.postRequest(hashMap, HttpURL);
return finalResult;
}
}
StudentRecordUpdateClass studentRecordUpdateClass = new StudentRecordUpdateClass();
studentRecordUpdateClass.execute(id,topic,description,event_date);
}
// Method to Delete Student Record
public void StudentDelete(final String ID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(), "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
Toast.makeText(getContext(), httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
getActivity().finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("Id", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpURLDelete);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(ID);
}
}
Try this set Adapter with empty list as soon as you initialize your ListView, then just add data to list and call notifyDataSetChanged() on adapter
Make list global
List<Map<String, String>> data2 = new ArrayList<Map<String, String>>();
Then in onCreateView, add below code under listview initialization
list4=(ListView)view.findViewById(R.id.list4);
adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
list4.setAdapter(adapter);
Then in onPostExecute of your AsyncTask, clear the existing list and new data,then just call notifyDataSetChanged() as in
#Override
protected void onPostExecute(String result) {
data2.clear(); //< --add this
json_string = result;
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
if (jsonArray.length() != 0) {
for (count = 0; count < jsonArray.length(); count++) {
JO = jsonArray.getJSONObject(count);
HashMap<String, String> datanum = new HashMap<String, String>();
datanum.put("A",JO.getString("Id"));
datanum.put("B",JO.getString("Topic"));
datanum.put("C",JO.getString("Description"));
datanum.put("D",JO.getString("Event_Date"));
data2.add(datanum);
}
adapter.notifyDataSetChanged(); //< --- call this
}
} catch (JSONException e) {
e.printStackTrace();
}
pdLoading.dismiss();
}
Related
RecyclerView is updated after the search and mCallback returns null but before search works correctly.
AdapterHistorico.java
package com.beliasdev.cadjobel.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.beliasdev.cadjobel.R;
import com.beliasdev.cadjobel.utility.DrawableHelper;
import com.bumptech.glide.Glide;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class AdapterHistorico extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Spinner spinner1;
private String dateold;
private String datenew;
private String compareValue;
private String concluido;
private String em_andamento;
private String cancelado;
private String concluido1;
private String em_andamento1;
private String cancelado1;
private String status;
private Context context;
private LayoutInflater inflater;
private IProcessFilter mCallback;
private ArrayList<DataHistorico> data;
//List<DataHistorico> data= Collections.emptyList();
DataHistorico current;
int currentPos=0;
public AdapterHistorico(Context context, ArrayList<DataHistorico> data, IProcessFilter callback){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
mCallback = callback;
}
public interface IProcessFilter {
void onProcessFilter(DataHistorico produtos);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_historico, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final DataHistorico pedidos = data.get(position);
values from list
MyHolder myHolder= (MyHolder) holder;
final DataHistorico current = data.get(position);
dateold = current.pData;
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'ás' HH:mm:ss");
datenew = df2.format(format.parse(dateold));
} catch (ParseException e) {
e.printStackTrace();
}
myHolder.txtPedidoNumero.setText("N° " + current.pNumero);
myHolder.txtPedidoCliente.setText(current.pCliente);
myHolder.txtPedidoData.setText(datenew);
myHolder.txtPedidoTotal.setText("R$ " + current.pTotal);
myHolder.edtPedido.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCallback.onProcessFilter(pedidos); //NullPointerException here
}
});
// load image into imageview using glide
concluido = "concluido";
cancelado = "cancelado";
em_andamento= "em_andamento";
status = current.pStatus;
if (status.equals(concluido)) {
Glide.with(context).load(R.drawable.ic_pedido_concluido).into(myHolder.imgPedidoStatus);
} else if (status.equals(cancelado)) {
Glide.with(context).load(R.drawable.ic_pedido_cancelado).into(myHolder.imgPedidoStatus);
}else if (status.equals(em_andamento)) {
Glide.with(context).load(R.drawable.ic_pedido_em_andamento).into(myHolder.imgPedidoStatus);
}
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView txtPedidoNumero;
TextView txtPedidoCliente;
ImageView imgPedidoStatus;
TextView txtPedidoData;
TextView txtPedidoTotal;
ImageView edtPedido;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
txtPedidoNumero= (TextView) itemView.findViewById(R.id.txtPedidoNumero);
txtPedidoCliente= (TextView) itemView.findViewById(R.id.txtPedidoCliente);
imgPedidoStatus= (ImageView) itemView.findViewById(R.id.imgPedidoStatus);
txtPedidoData = (TextView) itemView.findViewById(R.id.txtPedidoData);
txtPedidoTotal = (TextView) itemView.findViewById(R.id.txtPedidoTotal);
edtPedido = (ImageView) itemView.findViewById(R.id.edtPedido);
}
}
}
FragmentoHistorico.java
public class FragmentoHistorico extends Fragment implements AdapterHistorico.IProcessFilter {
[...]
public void onProcessFilter(DataHistorico pedidos) {
EditarPedidoDialog(pedidos);
}
private void EditarPedidoDialog(final DataHistorico pedidos){
LayoutInflater inflater = LayoutInflater.from(getActivity());
final View subView = inflater.inflate(R.layout.layout_edt_pedido, null);
[...]
private class ProcurarPedido extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
private String searchQuery;
private View rootView;
public ProcurarPedido(String searchQuery, View rootView){
this.searchQuery=searchQuery;
this.rootView=rootView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tAguarde...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL(ADMIN_PANEL_URL + "public/procurar-pedido-app.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Erro na conexão!");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
Log.v("result", result);
pdLoading.dismiss();
ArrayList<DataHistorico> data=new ArrayList<>();
if(result.equals("no rows")) {
mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
mAdapter = new AdapterHistorico(getActivity(), data, null);
mRVHistoricoInfo.setAdapter(mAdapter);
mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
data.clear();
Toast.makeText(getActivity(), "Não foram encontrados pedidos pelo nome do cliente informado.", Toast.LENGTH_LONG).show();
}else{
try {
data.clear();
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataHistorico historicoData = new DataHistorico();
historicoData.pNumero= json_data.getString("nid");
historicoData.pStatus= json_data.getString("pedido_status");
historicoData.pCliente= json_data.getString("pedido_cliente");
historicoData.pEndereco= json_data.getString("pedido_endereco");
historicoData.pData= json_data.getString("pedido_data");
historicoData.pTotal= json_data.getString("pedido_total");
data.add(historicoData);
}
mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
mAdapter = new AdapterHistorico(getActivity(), data, null);
mRVHistoricoInfo.setAdapter(mAdapter);
mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show();
}
}
}
}
[...]
This is the error:
java.lang.NullPointerException: Attempt to invoke interface method
'void
com.beliasdev.cadjobel.adapter.AdapterHistorico$IProcessFilter.onProcessFilter(com.beliasdev.cadjobel.adapter.DataHistorico)'
on a null object reference
You are sending null instead of listener as a parameter:
So change
mAdapter = new AdapterHistorico(getActivity(), data, null);
To
mAdapter = new AdapterHistorico(getActivity(), data, this);
i am working on json parsing where in my TypeMenu java file i am getting response from server and when i click on the item in listview i should get related item in the next activity in listview ..that listview item is also coming from server...here i want to get item only from selected item..but i am getting all item from database in my next activity which is SubMenu.java...like if i select Pizza so in next activity i should get item related with pizza only
Here is my TypeMenu.java file
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class TypeMenu extends AppCompatActivity {
private String TAG = TypeMenu.class.getSimpleName();
String bid;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/brtemp/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String keyId = new ArrayList<>(selected.keySet()).get(0);
String type_items = selected.get(keyId);
Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
in.putExtra(TAG_BID ,type_items );
startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" +type_items ,Toast.LENGTH_LONG).show();
}
});
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TypeMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("type", type);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{ "type","id"},
new int[]{
R.id.type,R.id.id});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my SubMenu.java file
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SubMenu extends AppCompatActivity {
private String TAG = SubMenu.class.getSimpleName();
String type_items ;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/broccoli/menu_typeitem.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = getIntent();
// getting product id (pid) from intent
type_items = i.getStringExtra(TAG_BID);
Toast.makeText(getApplicationContext(),"Toast 12" + type_items ,Toast.LENGTH_LONG).show();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pDialog = new ProgressDialog(SubMenu.this);
pDialog.setMessage("Loading book details.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String keyId = new ArrayList<>(selected.keySet()).get(0);
String type_items = selected.get(keyId);
//Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
// in.putExtra(TAG_BID ,text);
//startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" + type_items,Toast.LENGTH_LONG).show();
}
});
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SubMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SubMenu.this, contactList,
R.layout.list_item, new String[]{ "name","id"},
new int[]{
R.id.type});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my php file..i know it will show all the data ..i tried other code also but not working ..in this atleast all data from table is showing..but i want only selected data
<?php
if($_SERVER['REQUEST_METHOD']=='GET')
{
$id = $_GET['type_items'];
require_once('config.php');
$sql = "SELECT * FROM main_menu_items WHERE type_item='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array("name"=>$res['name'],)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
replace for loop of GetContacts of SubMenu.java class with below :
for (int i = 0; i < jsonArry.length(); i++) {
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String type = c.getString("type");
if (type.equalsIgnoreCase(type_items)) {
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contactList.add(contact);
break;
}
}
In submenu class you need to check if the selected ID matches with the id just save that data in list and break the loop.
I need to pass the brand id values of my json response as a parameter to http request using shared preference.I also need to store the brand id values in my main Activity and retreive it in my AddVehicle activity Please help me.Can i use arraylist? If yes, Then say me how? The id should check with the corresponding name and it should be displayed on my 2nd activity(AddVehicle)
Currently i have passed only one brand detail in my main Activity,but instead i need to pass all the id dynamically under one common variable?
My API response
{
"status": 1,
"data": [
{
"id": 1,----> brand id
"name": "AUDI",
"code": "AUDI",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:07:38",
"updated_at": "2016-09-27 00:07:38"
},
{
"id": 2-----> brand id
"name": "Bravian Motor Works",
"code": "BMW",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:07:58",
"updated_at": "2016-09-27 00:07:58"
},
{
"id": 3,---->brand id
"name": "AB Volvo",
"code": "VOLVO",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:08:36",
"updated_at": "2016-09-27 00:08:36"
},
{
"id": 4,-----> brand id
"name": "Ford Motor Company",
"code": "FORD",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:11:51",
"updated_at": "2016-09-27 00:11:51"
},
{
"id": 5,-----> brand id
"name": "Maruti Suzuki",
"code": "Maruti",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:12:14",
"updated_at": "2016-09-27 00:12:14"
}
],
"msg": "success",
"info": "data list"
}
MainActivity
package com.example.addvehicle;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
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 org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.addvehicle.R.string.brand;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
ArrayList<String> brandListArray = new ArrayList<String>();
ArrayList<String> modelListArray = new ArrayList<String>();
Button addVehicleBtn;
EditText AddVehicle_Regno, kmscovered;
RadioButton petrol, Diesel, fullyloaded, Basicmodel;
TextView textView8, textViewkms;
Spinner AddspinnerMake, AddspinnerModel, AddspinnerYear;
private static String url = "http://garage.kaptastech.mobi/api/5k/master/vehicle";
private String[] values;
ArrayList<String> brandListId;
ArrayList<String> modelListId;
String brandid;
String modelId;
ArrayList<HashMap<String, String>> addVehiclelist;
String jsonStr;
String Regno, fuelType, Brand, Year, Model, variant;
/**
* 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_main);
brandListArray = new ArrayList<String>();
brandListId = new ArrayList<String>();
modelListArray = new ArrayList<String>();
modelListId = new ArrayList<String>();
addVehiclelist = new ArrayList<HashMap<String, String>>();
petrol = (RadioButton) findViewById(R.id.petrol);
Diesel = (RadioButton) findViewById(R.id.diesel);
fullyloaded = (RadioButton) findViewById(R.id.fullyLoaded);
Basicmodel = (RadioButton) findViewById(R.id.basicmodel);
addVehicleBtn = (Button) findViewById(R.id.addVehicleBtn);
AddVehicle_Regno = (EditText) findViewById(R.id.AddVehicle_Regno);
kmscovered = (EditText) findViewById(R.id.kmsCovered);
textView8 = (TextView) findViewById(R.id.textView8);
textViewkms = (TextView) findViewById(R.id.textViewkms);
AddspinnerMake = (Spinner) findViewById(R.id.AddspinnerMake);
AddspinnerModel = (Spinner) findViewById(R.id.AddspinnerModel);
AddspinnerYear = (Spinner) findViewById(R.id.AddspinnerYear);
new Getbrands().execute();
petrol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (petrol.isChecked()) {
fuelType = petrol.getText().toString();
}
}
});
Diesel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (Diesel.isChecked()) {
fuelType = Diesel.getText().toString();
}
}
});
AddspinnerMake.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
Brand = AddspinnerMake.getSelectedItem().toString();
if (position > 0) {
brandid = brandListId.get(position).toString();
//**Get Model execute api//
new Getmodels().execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
AddspinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Year = AddspinnerYear.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
AddspinnerModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
Model = AddspinnerModel.getSelectedItem().toString();
if (position > 0) {
modelId = modelListId.get(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Basicmodel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (Basicmodel.isChecked()) {
variant = Basicmodel.getText().toString();
}
}
});
fullyloaded.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (fullyloaded.isChecked()) {
variant = fullyloaded.getText().toString();
}
}
});
addVehicleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Regno = AddVehicle_Regno.getText().toString();
new GetVehicle().execute();
Intent intent = new Intent(MainActivity.this, AddVehicle.class);
startActivity(intent);
}
});
// 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();
}
/**
* 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("Main 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();
}
private class GetVehicle extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://garage.kaptastech.mobi/api/5k/master/vehicle");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(7);
nameValuePair.add(new BasicNameValuePair("user_id","5"));
nameValuePair.add(new BasicNameValuePair("registration_no", Regno));
nameValuePair.add(new BasicNameValuePair("brand","5"));
nameValuePair.add(new BasicNameValuePair("model", "4"));
nameValuePair.add(new BasicNameValuePair("type", "2"));
nameValuePair.add(new BasicNameValuePair("variant", "2"));
nameValuePair.add(new BasicNameValuePair("year", Year));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = client.execute(httpPost);
// writing response to log
Log.d("Response from url:", response.toString());
jsonStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
/*HttpConnection ht = new HttpConnection();
ht.getVehicle();*/
JSONObject object = new JSONObject(jsonStr);
JSONArray Vehicle = object.getJSONArray("data");
for (int i = 0; i < Vehicle.length(); i++) {
JSONObject c = Vehicle.getJSONObject(i);
String Regno = c.getString("registration_no");
String brand = c.getString("brand");
String model = c.getString("model");
String fueltype = c.getString("type");
String variant = c.getString("variant");
HashMap<String, String> Vl = new HashMap<String, String>();
Vl.put("registration_no", Regno);
Vl.put("brand", brand);
Vl.put("model", model);
Vl.put("type", fueltype);
Vl.put("variant:", variant);
addVehiclelist.add(Vl);
values = new String[]{
"Registration No:" + Regno,
"Brand:" + brand,
"Model:" + model,
"Type:" + fueltype,
"Variant:" + variant,
};
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
private class Getbrands extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://garage.kaptastech.mobi/api/5k/master/brand");
try {
HttpResponse response = client.execute(httpGet);
// writing response to log
Log.d("Response from url:", response.toString());
jsonStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpConnection ht = new HttpConnection();
ht.getbrand();
JSONObject object = new JSONObject(jsonStr);
JSONArray brandArray = object.getJSONArray("data");
brandListArray.clear();
brandListId.clear();
brandListArray.add("Select Brand");
brandListId.add("0");
for (int i = 0; i < brandArray.length(); i++) {
JSONObject gb = brandArray.getJSONObject(i);
brandListArray.add(gb.getString("name"));
brandListId.add(gb.getString("id"));
String[] brandStringArray = new String[brandListArray.size()];
brandStringArray = brandListArray.toArray(brandStringArray);
for (int i1 = 0; i1 < brandStringArray.length; i1++) {
Log.d("String is", (String) brandStringArray[i1]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, brandListArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AddspinnerMake.setAdapter(adapter);
}
}
private class Getmodels extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://garage.kaptastech.mobi/api/5k/master/models/" + brandid);
try {
HttpResponse response = client.execute(httpGet);
// writing response to log
Log.d("Response from url:", response.toString());
jsonStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpConnection ht = new HttpConnection();
ht.getmodel();
JSONObject object = new JSONObject(jsonStr);
JSONArray modelArray = object.getJSONArray("data");
modelListArray.clear();
modelListId.clear();
modelListArray.add("Select Model");
modelListId.add("0");
for (int i = 0; i < modelArray.length(); i++) {
JSONObject gm = modelArray.getJSONObject(i);
modelListArray.add(gm.getString("name"));
modelListId.add(gm.getString("id"));
String[] modelStringArray = new String[modelListArray.size()];
modelStringArray = modelListArray.toArray(modelStringArray);
for (int i2 = 0; i2 < modelStringArray.length; i2++) {
Log.d("String is", (String) modelStringArray[i2]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, modelListArray);
AddspinnerModel.setAdapter(adapter);
}
}
}
And i need to retreive it on my AddVehicle Activity
AddVehicleActivity
package com.example.addvehicle;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AddVehicle extends AppCompatActivity {
ListView addVehicleListView;
ArrayList<HashMap<String, String>> VehicleList;
ArrayList<String> brandListId;
private String[] values;
private static String urlString = "http://garage.kaptastech.mobi/api/5k/users/vehicle";
private String TAG = AddVehicle.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
brandListId = new ArrayList<String>();
VehicleList = new ArrayList<HashMap<String, String>>();
addVehicleListView = (ListView) findViewById(R.id.addVehicleListView);
new GetVehicle().execute();
}
private class GetVehicle extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpConnection ht = new HttpConnection();
String response = ht.getVehicle();
{
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://garage.kaptastech.mobi/api/5k/users/vehicle");
JSONObject Object = new JSONObject(response);
JSONArray Vehicle = Object.getJSONArray("data");
for (int i = 0; i < Vehicle.length(); i++) {
JSONObject c = Vehicle.getJSONObject(i);
String Regno = c.getString("registration_no");
String brand = c.getString("brand_id");
String model = c.getString("model_id");
String fueltype = c.getString("type");
String variant = c.getString("variant");
HashMap<String, String> Vl = new HashMap<String, String>();
Vl.put("registration_no", Regno);
Vl.put("brand_id", brand);
Vl.put("model_id", model);
Vl.put("type", fueltype);
Vl.put("variant:" , variant);
VehicleList.add(Vl);
values = new String[]{
"Registration No:" + Regno,
"Brand Id:" + brand,
"Model Id:" + model,
"Type:" + fueltype,
"Variant:" + variant,
};
}
} catch (final Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddVehicle.this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
//ListAdapter adapter = new SimpleAdapter(AddVehicle.this, VehicleList, R.layout.activity_list, new String[]{"brand_id", "model_id", "registration_no", "type", "variant"}, new int[]{R.id.AddspinnerMake, R.id.AddspinnerModel, R.id.AddVehicle_Regno, R.id.fullyLoaded, R.id.basicmodel});
addVehicleListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
I tried to implement for adding more items to my adapter but its refreshing every time instead of adding new items to bottom of the list.I searched through the internet but i didn't get the solution Here is my code:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private DataListAdapter dataListAdapter;
Activity _activity;
ArrayList<DataObject> dataArrayList;
private ListView lv;
private String jsonResult;
boolean loadingMore = false;
private DataObject dataObject;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
lv = (ListView) findViewById(R.id.listView1);
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
this.lv.addFooterView(footerView);
if (isOnline(_activity)) {
new LoadJsonData().execute();
scrollNotifyChange();
}
}
private void scrollNotifyChange() {
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already? Load more!
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
// //start a new thread for loading the items in the list
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
}
private Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
//Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
jsonResult = doInBackground();
runOnUiThread(returnRes);
}
};
private Runnable returnRes = new Runnable() {
#Override
public void run() {
onPostExecute(jsonResult);
loadingMore = false;
}
};
public String doInBackground() {
String jsonResult = "";
// jsonResult=get("https://datatables.net/examples/server_side/scripts/server_processing.php");
// return jsonResult;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
public void onPostExecute(String result) {
try {
// progress.dismiss();
dataArrayList = new ArrayList<DataObject>();
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
dataListAdapter = new DataListAdapter(dataArrayList);
dataListAdapter.add(dataObject);
// lv.setAdapter(dataListAdapter);
// dataListAdapter.add(dataObject);
dataListAdapter.notifyDataSetChanged();
lv.setAdapter(dataListAdapter);
lv.smoothScrollToPosition(dataListAdapter.getCount());
} catch (JSONException e) {
e.printStackTrace();
}
}
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class LoadJsonData extends AsyncTask<Void, Void, String> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(_activity, "Progress",
"Please wait", true);
}
#Override
protected String doInBackground(Void... params) {
String jsonResult = "";
// jsonResult=get("https://datatables.net/examples/server_side/scripts/server_processing.php");
// return jsonResult;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
progress.dismiss();
if(loadingMore)
{
// listViwe.removeFooterView(loadingFooter);
loadingMore = false;
}
dataArrayList = new ArrayList<DataObject>();
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
DataObject dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
dataListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
if(loadingMore)
{
// listViwe.removeFooterView(loadingFooter);
loadingMore = false;
}
}
}
}
public class DataListAdapter extends BaseAdapter {
ArrayList<DataObject> dataListObject = new ArrayList<DataObject>();
public DataListAdapter(ArrayList<DataObject> dataListObject) {
this.dataListObject = dataListObject;
}
#Override
public int getCount() {
return dataListObject.size();
}
#Override
public Object getItem(int position) {
return dataListObject.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void add(DataObject dataObject){
// Log.v("AddView", country.getCode());
this.dataListObject.add(dataObject);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(_activity);
convertView = inflater.inflate(R.layout.single_row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.type = (TextView) convertView.findViewById(R.id.type);
holder.profession = (TextView) convertView.findViewById(R.id.profession);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.currency = (TextView) convertView.findViewById(R.id.currecy);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final DataObject current = dataListObject.get(position);
holder.name.setText("Name--" + current.getName());
holder.type.setText("Type--" + current.getType());
holder.profession.setText("Professoion--" + current.getProfession());
holder.country.setText("Country--" + current.getCountry());
holder.currency.setText("Currency--" + current.getCurrency());
return convertView;
}
}
static class ViewHolder {
TextView name;
TextView type;
TextView profession;
TextView country;
TextView currency;
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
return result;
}
}
you need to create an adapter inside onCreate method
like this:
ArrayList<DataObject> list;
onCreate() {
list=new ArrayList();
ListAdapter dataListAdapter =new ListAdapter(list) // creating an adapter with empty list of data
listView.setAdpater(adpater);
}
then, in onPostExceute() method :
add data to the ArrayList and notifythe adapter
like this:
onPostExecute(){
....
.....
list.add(dataObject); //here you can add 'n' number of object to the list
dataListAdapter.notifyDataSetChanged(); // notify the adapter to update the listview
.....
}
EDIT : I updated this answer as per #user3422948 request
DataListAdapter dataListAdapter;
ArrayList<DataObject> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
//edit: declare your arraylist and adapter here
dataArrayList = new ArrayList<DataObject>();
dataListAdapter = new DataListAdapter(dataArrayList);
lv = (ListView) findViewById(R.id.listView1);
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
this.lv.addFooterView(footerView);
if (isOnline(_activity)) {
new LoadJsonData().execute();
scrollNotifyChange();
}
}
......
.......
public void onPostExecute(String result) {
try {
// progress.dismiss();
//dataArrayList = new ArrayList<DataObject>(); //edit
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
//edit: your creating new adapter for every execution
//dataListAdapter = new DataListAdapter(dataArrayList);
//dataListAdapter.add(dataObject);
// lv.setAdapter(dataListAdapter);
// dataListAdapter.add(dataObject);
dataListAdapter.notifyDataSetChanged();
//lv.setAdapter(dataListAdapter);
lv.smoothScrollToPosition(dataListAdapter.getCount());
} catch (JSONException e) {
e.printStackTrace();
}
}
the problem is for every execution you are creating new Adapter
you should see this link how to use notifyDataSetChanged in listView
AsyncTask spawns a new intelligent thread on its own, runs things in background and also posts results of UI thread in onPostExecute method.
You should not call the methods of AsyncTask on your own. Android does it by itself. Instead of calling a new thread in scrollchangelistener,like:
Thread thread = new Thread(null, loadMoreListItems);
call
new LoadJsonData().execute();
you don't need two Runnable threads to do the same thing your asyncTask does.
The problem is this code of yours:
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
Every time your scrolling reaches the end, it eventually calls the onPostExecute method to post results on the UI. But here you are making a new Adapter eveytime with a new dataset which is why it always refreshes the whole list.
Remove this part and set it inside onCreate of your Activity.Add new values to your adapter's datalist in onPostExecute.
Then just do a notifyDataSetChanged inside onPostExecute of your AsyncTask.
I have a Recycler View which uses AsyncTask to populate UI.
Currently it retrieves all the data from the DB and displays it in one shot, but
I want to retrieve only 15 records in one go and after the scroll ends I want to load more 15 records and so on...can anybody please help. I have pasted the code below:
FeedActivity.java
package com.bbau.ankit.test_splash;
import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Window;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ankit on 8/14/2015.
*/
public class FeedListActivity extends Activity {
private static final String TAG = "RecyclerViewExample";
private List<FeedItem> feedItemList = new ArrayList<FeedItem>();
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Allow activity to show indeterminate progressbar */
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.news);
/* Initialize recyclerview */
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(Color.BLACK).build());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
/*Downloading data from below url*/
final String url = "http://192.168.170.72/bbau_news.php?before=1&after=5";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapter(FeedListActivity.this, feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("NEWS");
/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedItem>();
}
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("news_desc"));
item.setDescription(post.optString("Date"));
item.setUrl(post.optString("News"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
MyRecyclerAdapter.java
package com.bbau.ankit.test_splash;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.style.AlignmentSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by Ankit on 8/14/2015.
*/
public class MyRecyclerAdapter extends RecyclerView.Adapter<FeedListRowHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public FeedListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
FeedListRowHolder mh = new FeedListRowHolder(v);
mh.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("List Size", Integer.toString(getItemCount()));
TextView redditUrl = (TextView) v.findViewById(R.id.url);
String postUrl = redditUrl.getText().toString();
Log.d("The URL:", postUrl);
Intent intent = new Intent(mContext, WebViewActivity.class);
intent.putExtra("url", postUrl);
mContext.startActivity(intent);
}
});
return mh;
}
#Override
public void onBindViewHolder(FeedListRowHolder feedListRowHolder, int i) {
final FeedItem feedItem = feedItemList.get(i);
feedListRowHolder.title.setText(Html.fromHtml(feedItem.getTitle()));
feedListRowHolder.description.setText(feedItem.getDescription());
feedListRowHolder.url.setText(feedItem.getUrl());
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}
Of course you can use Recycler view and EndlessScrool as a combination like this..
Here is a sample
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loading = false;
Log.v("...", "Last Item Wow !");
}
}
}
});
Don't forget to add
LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
Here is a Github example: EndlessRecyclerOnScrollListener