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);
Related
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);
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;
}
}
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 am fetching data from movie database API and sometimes images do not load and sometimes it loads slowly. I am decoding images url to bitmap and then setting them to image view using adapter.Please tell where i am making mistake.I am getting images url right from API.
MainActivity.java:
package com.example.sahilshokeen.movie;
public class MainActivity extends Activity {
private RecyclerView recyclerView;
private GridLayoutManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//checking network
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
new FetchData().execute();
new Convert().execute();
} else {
// display error
Toast toast = Toast.makeText(this, "No Network", Toast.LENGTH_LONG);
toast.show();
}
//setting adapter
recyclerView = (RecyclerView) findViewById(R.id.recyclers);
manager = new GridLayoutManager(MainActivity.this, 2);
recyclerView.setAdapter(new Adapter());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(manager);
}
public class FetchData extends AsyncTask<Void, Void, Void> {
private HttpURLConnection connection = null;
private BufferedReader reader = null;
private String json;
private String urlString = "http://api.themoviedb.org/3/movie/popular?api_key=b6f6fcfbb225d8c500e4404655ccadcc&certification=G";
private String image = " http://image.tmdb.org/t/p/w92/";
#Override
protected Void doInBackground(Void... params) {
//connecting to network
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
StringBuffer buffer = new StringBuffer();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
json = buffer.toString();
//getting json data
try {
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("results");
for (int i = 0; i < 6; i++) {
Data.objects[i] = array.getJSONObject(i);
Data.title[i] = Data.objects[i].getString("original_title");
Data.overview[i] = Data.objects[i].getString("overview");
Data.date[i] = Data.objects[i].getString("release_date");
Data.image[i] = Data.objects[i].getString("poster_path");
Data.vote[i] = Data.objects[i].getDouble("vote_average");
Data.image[i] = image + Data.image[i];
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class Convert extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
for(int i=0;i<6;i++) {
try {
URL url = new URL(Data.image[i]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Data.bImage[i] = myBitmap;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_refresh) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter.java:
package com.example.sahilshokeen.movie;
public class Adapter extends RecyclerView.Adapter<Adapter.Holder> {
public static class Holder extends RecyclerView.ViewHolder {
public CardView cardView;
public ImageView imageView;
public Holder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.card);
imageView = (ImageView) itemView.findViewById(R.id.images);
}
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
Holder holder = new Holder(view);
return holder;
}
#Override
public void onBindViewHolder(Holder holder, int position) {
holder.imageView.setImageBitmap(Data.bImage[position]);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return Data.bImage.length;
}
}
Data.java:
package com.example.sahilshokeen.movie;
public class Data {
public static JSONObject[] objects = new JSONObject[6];
public static String[] title = new String[6];
public static String[] overview = new String[6];
public static String[] date = new String[6];
public static String[] image = new String[6];
public static Bitmap[] bImage = new Bitmap[6];
public static Double[] vote = new Double[6];
}
You are using InputStreamReader, which i think isn't necessary, It may as well be the reason why it is slow. I can't post this as a comment so I have to post as answer.
Try this code for doInBackground instead of using InputStreamReader.
//Call your method
new FetchData().execute("http://api.themoviedb.org/3/movie/popular?api_key=b6f6fcfbb225d8c500e4404655ccadcc&certification=G");
public class FetchData extends AsyncTask<String, Void, Void> {
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
//Get your data here Example : poster_path
object.getString("poster_path");
}
return true;
}
//------------------>>
} catch (ConnectTimeoutException e) {
Log.e("Timeout Exception: ", e.toString());
} catch (SocketTimeoutException ste) {
Log.e("Timeout Exception: ", ste.toString());
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
And you need to import this classes
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
Use Library Such as Glide Or Picasso.!
#Override
public void onBindViewHolder(Holder holder, int position) {
// holder.imageView.setImageBitmap(Data.bImage[position]);
Glide.with(ctx)
.load(imageDownloadUrl)
.into(holder.imageView);
Picasso.with(context).load("").placeholder(Data.bImage[position]).into(holder.imageView);
or
//R.drawable.drawableName
Picasso.with(context).load(Data.bImage[position]).into(holder.imageView);
}
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.android.support:support-v4:25.1.0'
I am new to Android development and am in the process of creating my first app. The app takes a picture, previews that picture, randomly selects a picture from the database to upload to the server and displays JSON text information in listview.
I am trying to use a custom list view adapter to allow the JSON information's corresponding picture to be in the LISTVIEW and NOT imageview.
I have thoroughly researched listview adapters to understand the syntax and where to place the code to implement the listview with a picture properly. However, I am receiving four error messages which prevent the code from compiling. I realize that there are other posts about similar topics on this website, but I have dug around them and tried to implement the states solutions with no success.
Below is my code:
public class JSONBuilderActivity extends ListActivity {
private ProgressDialog pDialog;
//URL to get JSON
private static String url = ".........";
//JSON Node names
private static final String TAG_CARS = "cars"; //root
private static final String TAG_CARID = "CarID";
private static final String TAG_CARVIN = "CarVIN";
private static final String TAG_IMG = "CarMainImage";
CustomListViewAdapter adapter;
JSONArray carid = null; //Initializes JSON array
private CustomListViewAdapter clva = null;
ListView lv;
List<Item> item = new ArrayList<JSONBuilderActivity.Item>();
static String response = null;
//Hashmap for ListView
ArrayList<HashMap<String, Object>> caridList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = getListView();
//ArrayList<Item> item;
lv.setAdapter(adapter);
lv = (ListView) findViewById(R.id.list_item);
adapter = new CustomListViewAdapter(this,item);
lv.setAdapter(adapter);
//Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Gets values from selected ListItem
String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
String car_vin = ((TextView) view.findViewById(R.id.car_vin)).getText().toString();
String model_img = ((ImageView) view.findViewById(R.id.model_img)).getTag().toString();
Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
//Sends data to MainActivity
in.putExtra("TAG_CARS", cars);
in.putExtra("TAG_CARID", car_id);
in.putExtra("TAG_CarVin", car_vin);
in.putExtra("TAG_IMG", model_img);
startActivity(in);
}
});
//Calls async task to get json
new GetCars().execute();
}
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Makes service call
*
* #url - url to make request
* #method - http request method
*/
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Makes service call
*
* #url - url to make request
* #method - http request method
* #params - http request params
*/
public String makeServiceCall(String url, int method, ArrayList<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//Checks http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
//Adds post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//Appends params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "CarMainImage", null);
return Uri.parse(path);
}
public void saveBmpToFile(File filename, Bitmap bmp) {
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean renameFileExtension(String source, String newExtension) {
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals("")) {
target = source + "." + newExtension;
} else {
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
public String getFileExtension(String f) {
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1) {
ext = f.substring(i + 1);
}
return ext;
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, Object>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String car_vin = c.getString(TAG_CARVIN);
Log.d("car_vin", car_vin);
String model_img = c.getString(TAG_IMG);
Log.d("model_img", model_img);
//CustomListViewAdapter adapter = new CustomListViewAdapter(this, R.layout.list_item, item);
// String model_img = c.getString(TAG_IMG);
//Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_CARVIN, car_vin);
matchGetCars.put(TAG_IMG, model_img);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
//ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
// new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
// setListAdapter(adapter);
ListView lv = (ListView)findViewById(R.id.list_item);
clva = new CustomListViewAdapter();
lv.setAdapter(clva);
}
}
public class CustomListViewAdapter extends ArrayAdapter<Item> {
private ArrayList<Item> objitem;
Activity context;
public CustomListViewAdapter(ArrayList<Item> item, int ResourceId, Activity context){
super(context, ResourceId, item);
this.context = context;
this.objitem = item;
}
private class ViewHolder {
ImageView model_img;
TextView car_id;
TextView car_vin;
}
public View getView ( int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
final Item item = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder.car_id = (TextView) convertView.findViewById(R.id.car_id);
holder.car_vin = (TextView) convertView.findViewById(R.id.car_vin);
holder.model_img = (ImageView) convertView.findViewById(R.id.model_img);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.car_id.setText(item.getVin());
holder.car_vin.setText(item.getId());
holder.model_img.setImageResource(item.getmodelimg());
return convertView;
}
}
public class Item {
private int model_img;
private String car_id;
private String car_vin;
public Item(int model_img, String car_id, String car_vin) {
this.model_img = model_img;
this.car_id = car_id;
this.car_vin = car_vin;
}
/* Getters
*/
public int getmodelimg() {
return model_img;
}
public String getVin() {
return car_vin;
}
public String getId() {
return car_id;
}
/* Setters
*/
public void setmodelimg(int model_img) {
this.model_img = model_img;
}
public void setVin(String car_vin) {
this.car_vin = car_vin;
}
public void setId(String car_id) {
this.car_id = car_id;
}
}
}
Error:
CustomListViewAdapter() cannot be applied to CustomListViewAdapter for:
adapter = new CustomListViewAdapter(this,item); in onCreate
Update:
adapter = new CustomListViewAdapter(this, R.id.list_view, item); in onCreate.'
I still receive the same (above) error.
Imports:
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
I am having trouble understanding what I am doing so incorrect. I appreciate any input. Thank you.
You're trying to instantiate the adapter which has this constructor
public CustomListViewAdapter(ArrayList<Item> item, int ResourceId, Activity context)
although you're calling it like this
adapter = new CustomListViewAdapter(this,item);
problem: the arguments don't match
It should be something like
adapter = new CustomListViewAdapter(item, R.layout.list_row, this);
note that list_row is something I made up and should be an actual layout file in your app or in the android sdk