Android ArrayAdapter class constructor have error - java

package rappiddevelopers.destinationadvisor;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
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.List;
import rappiddevelopers.destinationadvisor.models.TranslatorModel;
public class MainActivity extends AppCompatActivity {
private AutoCompleteTextView autoCompleteTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
new HttpGetTask().execute("http://192.168.0.107/abc/translator.php");
}
public class HttpGetTask extends AsyncTask<String, String, List<TranslatorModel>> {
#Override
protected List<TranslatorModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<TranslatorModel> translatorModelList = new ArrayList<>();
for(int i= 0; i<parentArray.length();i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
TranslatorModel translatorModel = new TranslatorModel();
translatorModel.setEnglish(finalObject.getString("englishSentence"));
translatorModelList.add(translatorModel);
}
return translatorModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<TranslatorModel> data) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(1);
super.onPostExecute(data);
}
}
}
Want to display value from json string object (englishSentence) into autocompleteTextview.
TranslatorModel class have getter and setter methods for jsonObjects.
Error found on arrayAdapter declaration line.

you are using the custom object not String hence you need to create custum adapter extending the ArrayAdapter like this
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}

Related

Interface returning null after doing search

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);

NullPointerExcepter Error when using List Adapter and Custom List View in Android Studio

Been trying to write an app in android studio. Part of the app has to parse a document in JSON and display two TextViews of data for each instance. One being Signal and the other being Noise. I am trying to make a custom list view in case I want to add more detail to each instance. I also would like to make it all contained in a ScrollView. I initially had no problems parsing the document but now that I am trying to implement the ListAdapter I am running into issues.
My code is giving me the error...
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yesinc.tsi880, PID: 4919
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.yesinc.tsi880.TelemetryActivity$JSONTask.onPostExecute(TelemetryActivity.java:136)
at com.yesinc.tsi880.TelemetryActivity$JSONTask.onPostExecute(TelemetryActivity.java:50)
Not sure if the problem is with the document that I am trying to parse or the java code itself. Any help would be much appreciated. Code is below.
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.yesinc.tsi880.models.SondeModel;
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.List;
import android.widget.ArrayAdapter;
public class TelemetryActivity extends AppCompatActivity {
private TextView tvData;
private ListView lvSondes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_telemetry);
ListView lvSondes = findViewById(R.id.lvSondes);
//new JSONTask().execute("http://172.16.5.70/plots/sigstr2.txt");
}
public class JSONTask extends AsyncTask<String, String, List<SondeModel> >{
#Override
protected List<SondeModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while((line=reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject parentArray0 = parentObject.getJSONObject("0");
JSONObject parentArray1 = parentObject.getJSONObject("1");
List<SondeModel> sondeModelList = new ArrayList<>();
//StringBuffer finalBufferedData = new StringBuffer();
for(int i=0; i<8; i++){
String sonde = String.valueOf(i);
JSONObject finalObject = parentArray0.getJSONObject(sonde);
SondeModel sondeModel = new SondeModel();
sondeModel.setNoisedbm(finalObject.getString("noisedbm"));
sondeModel.setSigdbm(finalObject.getString("sigdbm"));
//String noiseDBM = finalObject.getString("noisedbm");
//String sigDBM = finalObject.getString("sigdbm");
sondeModelList.add(sondeModel);
}
for(int i=0; i<8; i++){
String sonde = String.valueOf(i);
JSONObject finalObject = parentArray1.getJSONObject(sonde);
SondeModel sondeModel = new SondeModel();
sondeModel.setNoisedbm(finalObject.getString("noisedbm"));
sondeModel.setSigdbm(finalObject.getString("sigdbm"));
//String noiseDBM = finalObject.getString("noisedbm");
//String sigDBM = finalObject.getString("sigdbm");
sondeModelList.add(sondeModel);
}
return sondeModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<SondeModel> result) {
super.onPostExecute(result);
SondeAdapter adapter = new SondeAdapter(getApplicationContext(), R.layout.row, result);
lvSondes.setAdapter(adapter);
// TODO need to set a data to the List
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.navigation_telemetry) {
new JSONTask().execute("http://172.16.5.70/plots/sigstr2.txt");
return true;
}
return super.onOptionsItemSelected(item);
}
public class SondeAdapter extends ArrayAdapter{
public List<SondeModel> sondeModelList;
private int resource;
private LayoutInflater inflater;
public SondeAdapter(Context context, int resource, List<SondeModel> objects) {
super(context, resource, objects);
sondeModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(resource, null);
}
TextView sig;
TextView noise;
sig = (TextView)convertView.findViewById(R.id.sig);
noise = (TextView)convertView.findViewById(R.id.noise);
sig.setText(sondeModelList.get(position).getSigdbm());
noise.setText(sondeModelList.get(position).getNoisedbm());
return convertView;
}
}
}
ListView lvSondes = findViewById(R.id.lvSondes);
You are re-declaring the lvSondes inside your onCreate method. The class member list view is never used and is never initialized. Instead a local lvSondes is initialized. This variable will not be in scope and won't be visible to the AsyncTask. The async task will use the member variable and that will be null.
Solution: remove the ListView from the stated line and just initialize the member variable

How to add swipe-to-refresh in a list view

I am working on a news app and I want to update the ListView every time by swiping down in the MainActivity
This is the code of my MainActivity below:
package com.infinitystone.mani.news;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<News>> {
public static final String LOG_TAG = MainActivity.class.getName();
private static final int NEWS_LOADER_ID = 1;
private TextView mEmptyView;
private NewsAdapter mAdapter;
private static final String GUARDIAN_REQUEST_URL = "http://content.guardianapis.com/search?order-by=newest&show-fields=thumbnail&page-size=20&api-key=2f3badbb-4a58-44b8-9800-9ee2a0f445f9";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newsList = (ListView) findViewById(R.id.list);
mEmptyView = (TextView) findViewById(R.id.empty_view);
newsList.setEmptyView(mEmptyView);
mAdapter = new NewsAdapter(this, new ArrayList<News>());
newsList.setAdapter(mAdapter);
newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News currentNews = mAdapter.getItem(position);
Uri uri = Uri.parse(currentNews.getUrl());
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
builder.setSecondaryToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimaryDark));
builder.setShowTitle(true);
final Bitmap backButton = BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back_white_24dp);
builder.setCloseButtonIcon(backButton);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(MainActivity.this, uri);
}
});
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
}
else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyView.setText(R.string.no_internet);
}
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
// Create a new loader for the given URL
return new NewsLoader(this, GUARDIAN_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyView.setText(R.string.no_news);
mAdapter.clear();
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader<List<News>> loader) {
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
}
I have already added the android.support.v4.widget.SwipeRefreshLayout in my activity_main.xml file
How can I implement the SwipeRefreshLayout in java code ?
Code for fetching the news data:
package com.infinitystone.mani.news;
import android.text.TextUtils;
import android.util.Log;
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.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import static com.infinitystone.mani.news.MainActivity.LOG_TAG;
public class QueryUtils {
private QueryUtils() {
}
public static List<News> fetchNewsData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<News> news = extractFeaturesFromJson(jsonResponse);
return news;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<News> extractFeaturesFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject rootObject = new JSONObject(newsJSON);
JSONObject responseObject = rootObject.getJSONObject("response");
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject currentNews = resultsArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String titleUrl = currentNews.getString("webUrl");
String date = currentNews.getString("webPublicationDate");
JSONObject fields = currentNews.getJSONObject("fields");
String thumbnail = fields.getString("thumbnail");
News news1 = new News(title, thumbnail, date, titleUrl);
news.add(news1);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
return news;
}
}
Get a reference to your swipe to refresh layout.
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
swipeRefreshLayout.setOnRefreshListener(this);
// ... your other codes...
}
Now, make your activity implement the listener.
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<News>>, SwipeRefreshLayout.OnRefreshListener {
// ...
}
Finally implement those methods
#Override
public void onRefresh(){
swipeRefreshLayout.setRefreshing(true);
newsList = fetchNewsData(GUARDIAN_REQUEST_URL);
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
EDIT:
Here is the complete code for MainActivity. Please use this and let me know if this works.
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<News>>, SwipeRefreshLayout.OnRefreshListener {
public static final String LOG_TAG = MainActivity.class.getName();
private static final int NEWS_LOADER_ID = 1;
private TextView mEmptyView;
private NewsAdapter mAdapter;
private static final String GUARDIAN_REQUEST_URL = "http://content.guardianapis.com/search?order-by=newest&show-fields=thumbnail&page-size=20&api-key=2f3badbb-4a58-44b8-9800-9ee2a0f445f9";
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newsList = (ListView) findViewById(R.id.list);
mEmptyView = (TextView) findViewById(R.id.empty_view);
newsList.setEmptyView(mEmptyView);
mAdapter = new NewsAdapter(this, new ArrayList<News>());
newsList.setAdapter(mAdapter);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
swipeRefreshLayout.setOnRefreshListener(this);
newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News currentNews = mAdapter.getItem(position);
Uri uri = Uri.parse(currentNews.getUrl());
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
builder.setSecondaryToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimaryDark));
builder.setShowTitle(true);
final Bitmap backButton = BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back_white_24dp);
builder.setCloseButtonIcon(backButton);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(MainActivity.this, uri);
}
});
updateNewsList();
}
private void updateNewsList(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
}
else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyView.setText(R.string.no_internet);
}
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
// Create a new loader for the given URL
return new NewsLoader(this, GUARDIAN_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyView.setText(R.string.no_news);
mAdapter.clear();
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader<List<News>> loader) {
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
updateNewsList();
swipeRefreshLayout.setRefreshing(false);
}
}
Try this Respond to the Refresh Gesture, it should help.
as per my above comment use SwipeRefreshLayout
The SwipeRefreshLayout should be used whenever the user can refresh the contents of a view via a vertical swipe gesture. The activity that instantiates this view should add an OnRefreshListener to be notified whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout will notify the listener each and every time the gesture is completed again;
than set setOnRefreshListener to your SwipeRefreshLayout
void setOnRefreshListener (SwipeRefreshLayout.OnRefreshListener listener)
Set the listener to be notified when a refresh is triggered via the swipe gesture.
sample code
SwipeRefreshLayout mSwipeRefreshView;
mSwipeRefreshView = (SwipeRefreshLayout) findViewById(R.id.homeScreenSwipeRefreshView);
mSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// make your api request here
}
});
when your api request complted than use setRefreshing(false)
setRefreshing(boolean refreshing)
Notify the widget that refresh state has changed.
mSwipeRefreshView.setRefreshing(false);

How do I ensure that my list view element do not disappear when I change the orientation of my device?

I am building an app that displays details of a book you have searched. The problem is that every time I change the orientation of my device the list view elements disappear. I want help in how to make them not disappear. I have a feeling that I need to use a Loader but I have no idea in how to implement it. Here are my activities.
MainActivity :-
package com.example.visha.booklistingapp;
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.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BookAdapter mAdapter;
EditText searchtext;
ListView earthquakeListView;
TextView empty;
TextView authorcheck;
TextView titlecheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
earthquakeListView = (ListView) findViewById(R.id.listView);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
earthquakeListView.setAdapter(mAdapter);
searchtext = (EditText) findViewById(R.id.editText);
empty = (TextView) findViewById(R.id.textView);
earthquakeListView.setEmptyView(empty);
}
public void searchclick(View view) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
String parturl = searchtext.getText().toString();
parturl = parturl.replaceAll("\\s","");
StringBuilder urlbuilder = new StringBuilder();
urlbuilder.append(" https://www.googleapis.com/books/v1/volumes?q=");
urlbuilder.append(parturl);
urlbuilder.append("&maxResults=5");
String url = urlbuilder.toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(url); }
else{
Toast.makeText(getApplicationContext(), "You are not connected to the internet",
Toast.LENGTH_LONG).show();
}
}
private class BookAsyncTask extends AsyncTask<String, Void, List<Book>> {
#Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}
QueryUtils :-
package com.example.visha.booklistingapp;
import android.text.TextUtils;
import android.util.Log;
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.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by visha on 14-10-2016.
*/
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<Book> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Book> Books = extractFeatureFromJson(jsonResponse);
return Books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Book JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Book> extractFeatureFromJson(String BookJSON) {
if (TextUtils.isEmpty(BookJSON)) {
return null;
}
List<Book> Books = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(BookJSON);
JSONArray BookArray = baseJsonResponse.getJSONArray("items");
for (int i = 0; i < BookArray.length(); i++) {
JSONObject currentBook = BookArray.getJSONObject(i);
JSONObject properties = currentBook.getJSONObject("volumeInfo");
String author;
if(properties.has("authors")) {
author = properties.getString("authors");
}
else {
author = "";
}
String title = properties.getString("title");
Book Book = new Book(author, title);
Books.add(Book);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the Book JSON results", e);
}
return Books;
}
}
You need to override onSaveInstanceState and onRestoreInstanceState methods of Activity Class.
In onSaveInstanceState, save the list data into the Bundle.
In onRestoreInstanceState, restore the list with the Bundle data and re-create the list adapter.
Cheers!!!
if you do not have a different layout for the activity landscape mode then simply putting android:configChanges="orientation|screenLayout|screenSize" will do the job for you.
Example:
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenLayout|screenSize" />
and if you do have different layout for landscape mode the you need to override the savedInstanceState and save and restore the list accordingly in OnCreate

Load more items and add bottom to the list when scroll down in android

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.

Categories