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
Related
I have built my app with one URL and it worked correctly. But there's a problem from the unmatched return of "onCreateLoader" method in the MainActivity.java.
I use a background thread to load all data without problems. The onCreateLoader method in MainActivity.java should return Loader> and there's a class NewsLoader.java that extends AsyncTaskLoader>.
I want to return new NewsLoader in the onCreateLoader method but there's an error of unmatched return for this method, even tough I have done this before in another similar app.
MainActivity.java
package com.example.newsapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.app.LoaderManager.LoaderCallbacks;
import android.app.LoaderManager;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Event>> {
private EventAdapter mAdapter;
private static final int LOADER_ID = 1;
private static final String REQUEST_URL_1 = "http://content.guardianapis.com/search?q=debates&api-key=test\n";
private static final String REQUEST_URL_2 = "https://content.guardianapis.com/search?q=debate&tag=politics/politics&from-date=2014-01-01&api-key=test\n";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView earthquakeListView = findViewById(R.id.list_of_news);
mAdapter = new EventAdapter(this, new ArrayList<Event>());
earthquakeListView.setAdapter(mAdapter);
earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Event currentEvent = mAdapter.getItem(position);
assert currentEvent != null;
Uri eventUri = Uri.parse(currentEvent.getURL());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, eventUri);
startActivity(websiteIntent);
}
});
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#NonNull
#Override
public Loader<List<Event>> onCreateLoader(int id, Bundle args) {
return new NewsLoader(MainActivity.this, REQUEST_URL_1, REQUEST_URL_2);
}
#Override
public void onLoadFinished(Loader<List<Event>> loader, List<Event> news) {
mAdapter.clear();
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader<List<Event>> loader) {
mAdapter.clear();
}
}
NewsLoader.java
package com.example.newsapp;
import android.content.Context;
import androidx.loader.content.AsyncTaskLoader;
import java.util.List;
public class NewsLoader extends AsyncTaskLoader<List<Event>> {
private static final String LOG_TAG = NewsLoader.class.getName();
private String mUrl1;
private String mUrl2;
public NewsLoader(Context context, String url1, String url2) {
super(context);
mUrl1 = url1;
mUrl2 = url2;
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public List<Event> loadInBackground() {
if (mUrl1 == null && mUrl2 == null) { return null; }
// Perform the network request, parse the response, and extract a list of earthquakes.
List<Event> news = QueryUtils.fetchNewsData(mUrl1, mUrl2);
return news;
}
}
QueryUtils.java
package com.example.newsapp;
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.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class QueryUtils {
private static final String LOCATION_SEPARATOR = "T";
public static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<Event> fetchNewsData(String requestUrl1, String requestUrl2) {
URL url1 = createUrl(requestUrl1);
URL url2 = createUrl(requestUrl2);
String jsonResponse1 = null;
String jsonResponse2 = null;
try {
jsonResponse1 = makeHttpRequest(url1);
jsonResponse2 = makeHttpRequest(url2);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Event> news = extractEvents(jsonResponse1, jsonResponse2);
return news;
}
public static List<Event> extractEvents(String eventJSON1, String eventJSON2) {
// verify that there's data in one link at list
if (TextUtils.isEmpty(eventJSON1) && TextUtils.isEmpty(eventJSON2)) {
return null;
}
List<Event> news = new ArrayList<>();
try {
//getting results array from first link
JSONObject baseJsonResponse1 = new JSONObject(eventJSON1);
JSONObject mainObject1 = baseJsonResponse1.getJSONObject("response");
JSONArray eventArray1 = mainObject1.getJSONArray("results");
//getting results array from second link
JSONObject baseJsonResponse2 = new JSONObject(eventJSON2);
JSONObject mainObject2 = baseJsonResponse2.getJSONObject("response");
JSONArray eventArray2 = mainObject2.getJSONArray("results");
// reading required data from array of first link
for (int i = 0; i<eventArray1.length(); i++){
JSONObject currentEvent = eventArray1.getJSONObject(i);
//getting url
String webUrl = currentEvent.getString("webUrl");
//getting title
String webTitle = currentEvent.getString("webTitle");
//getting sectionName
String sectionName = currentEvent.getString("sectionName");
//getting webPublicationDate
String webPublicationDate = currentEvent.getString("webPublicationDate");
String date = "0000 - 00 - 00";
String time = "00:00:00";
if (webPublicationDate.contains(LOCATION_SEPARATOR)) {
String[] parts = webPublicationDate.split(LOCATION_SEPARATOR);
date = parts[0];
time = parts[1].substring(0, parts[1].length() - 1);
}
// Make Quake Of the Strings And Assigning it to earthquakes ArrayList<Quake>
Event quake = new Event(sectionName, webTitle, date, time, webUrl);
news.add(quake);
}
// reading required data from array of first link
for (int i = 0; i<eventArray2.length(); i++){
JSONObject currentEvent = eventArray2.getJSONObject(i);
//getting url
String webUrl = currentEvent.getString("webUrl");
//getting title
String webTitle = currentEvent.getString("webTitle");
//getting sectionName
String sectionName = currentEvent.getString("sectionName");
//getting webPublicationDate
String webPublicationDate = currentEvent.getString("webPublicationDate");
String date = "0000 - 00 - 00";
String time = "00:00:00";
if (webPublicationDate.contains(LOCATION_SEPARATOR)) {
String[] parts = webPublicationDate.split(LOCATION_SEPARATOR);
date = parts[0];
time = parts[1].substring(0, parts[1].length() - 1);
}
// Make Quake Of the Strings And Assigning it to earthquakes ArrayList<Quake>
Event quake = new Event(sectionName, webTitle, date, time, webUrl);
news.add(quake);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
// Return the list of earthquakes
return news;
}
private static URL createUrl(String requestUrl) {
URL url = null;
try {
url = new URL(requestUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
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.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
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 earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}
I have found a solution.
the problem here is that Loader has been deprecated in 28-API. So, one cannot use androidx with it.
The solution here is in NewsLoader.java:
Replace: import androidx.loader.content.AsyncTaskLoader;
with: import android.content.AsyncTaskLoader;
If one needs to use a newer way: use ViewrModels
RecyclerView is updated after the search and mCallback returns null but before search works correctly.
AdapterHistorico.java
package com.beliasdev.cadjobel.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.beliasdev.cadjobel.R;
import com.beliasdev.cadjobel.utility.DrawableHelper;
import com.bumptech.glide.Glide;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class AdapterHistorico extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Spinner spinner1;
private String dateold;
private String datenew;
private String compareValue;
private String concluido;
private String em_andamento;
private String cancelado;
private String concluido1;
private String em_andamento1;
private String cancelado1;
private String status;
private Context context;
private LayoutInflater inflater;
private IProcessFilter mCallback;
private ArrayList<DataHistorico> data;
//List<DataHistorico> data= Collections.emptyList();
DataHistorico current;
int currentPos=0;
public AdapterHistorico(Context context, ArrayList<DataHistorico> data, IProcessFilter callback){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
mCallback = callback;
}
public interface IProcessFilter {
void onProcessFilter(DataHistorico produtos);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_historico, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final DataHistorico pedidos = data.get(position);
values from list
MyHolder myHolder= (MyHolder) holder;
final DataHistorico current = data.get(position);
dateold = current.pData;
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'ás' HH:mm:ss");
datenew = df2.format(format.parse(dateold));
} catch (ParseException e) {
e.printStackTrace();
}
myHolder.txtPedidoNumero.setText("N° " + current.pNumero);
myHolder.txtPedidoCliente.setText(current.pCliente);
myHolder.txtPedidoData.setText(datenew);
myHolder.txtPedidoTotal.setText("R$ " + current.pTotal);
myHolder.edtPedido.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCallback.onProcessFilter(pedidos); //NullPointerException here
}
});
// load image into imageview using glide
concluido = "concluido";
cancelado = "cancelado";
em_andamento= "em_andamento";
status = current.pStatus;
if (status.equals(concluido)) {
Glide.with(context).load(R.drawable.ic_pedido_concluido).into(myHolder.imgPedidoStatus);
} else if (status.equals(cancelado)) {
Glide.with(context).load(R.drawable.ic_pedido_cancelado).into(myHolder.imgPedidoStatus);
}else if (status.equals(em_andamento)) {
Glide.with(context).load(R.drawable.ic_pedido_em_andamento).into(myHolder.imgPedidoStatus);
}
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView txtPedidoNumero;
TextView txtPedidoCliente;
ImageView imgPedidoStatus;
TextView txtPedidoData;
TextView txtPedidoTotal;
ImageView edtPedido;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
txtPedidoNumero= (TextView) itemView.findViewById(R.id.txtPedidoNumero);
txtPedidoCliente= (TextView) itemView.findViewById(R.id.txtPedidoCliente);
imgPedidoStatus= (ImageView) itemView.findViewById(R.id.imgPedidoStatus);
txtPedidoData = (TextView) itemView.findViewById(R.id.txtPedidoData);
txtPedidoTotal = (TextView) itemView.findViewById(R.id.txtPedidoTotal);
edtPedido = (ImageView) itemView.findViewById(R.id.edtPedido);
}
}
}
FragmentoHistorico.java
public class FragmentoHistorico extends Fragment implements AdapterHistorico.IProcessFilter {
[...]
public void onProcessFilter(DataHistorico pedidos) {
EditarPedidoDialog(pedidos);
}
private void EditarPedidoDialog(final DataHistorico pedidos){
LayoutInflater inflater = LayoutInflater.from(getActivity());
final View subView = inflater.inflate(R.layout.layout_edt_pedido, null);
[...]
private class ProcurarPedido extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
private String searchQuery;
private View rootView;
public ProcurarPedido(String searchQuery, View rootView){
this.searchQuery=searchQuery;
this.rootView=rootView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tAguarde...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL(ADMIN_PANEL_URL + "public/procurar-pedido-app.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Erro na conexão!");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
Log.v("result", result);
pdLoading.dismiss();
ArrayList<DataHistorico> data=new ArrayList<>();
if(result.equals("no rows")) {
mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
mAdapter = new AdapterHistorico(getActivity(), data, null);
mRVHistoricoInfo.setAdapter(mAdapter);
mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
data.clear();
Toast.makeText(getActivity(), "Não foram encontrados pedidos pelo nome do cliente informado.", Toast.LENGTH_LONG).show();
}else{
try {
data.clear();
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataHistorico historicoData = new DataHistorico();
historicoData.pNumero= json_data.getString("nid");
historicoData.pStatus= json_data.getString("pedido_status");
historicoData.pCliente= json_data.getString("pedido_cliente");
historicoData.pEndereco= json_data.getString("pedido_endereco");
historicoData.pData= json_data.getString("pedido_data");
historicoData.pTotal= json_data.getString("pedido_total");
data.add(historicoData);
}
mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
mAdapter = new AdapterHistorico(getActivity(), data, null);
mRVHistoricoInfo.setAdapter(mAdapter);
mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show();
}
}
}
}
[...]
This is the error:
java.lang.NullPointerException: Attempt to invoke interface method
'void
com.beliasdev.cadjobel.adapter.AdapterHistorico$IProcessFilter.onProcessFilter(com.beliasdev.cadjobel.adapter.DataHistorico)'
on a null object reference
You are sending null instead of listener as a parameter:
So change
mAdapter = new AdapterHistorico(getActivity(), data, null);
To
mAdapter = new AdapterHistorico(getActivity(), data, this);
I am working on 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);
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 need help.
just want to know how to pass value to my php using JSON?
in my CategoryFragment code i set value to my cid
cid = catid;
now i want to pass this value to my php using JSON in this code
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
this is my CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONArray jsonarray;
GridView productgridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productgridview = (GridView) rootView.findViewById(R.id.productgridview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new GridViewAdapter(getActivity(), arraylist);
// Set the adapter to the GridView
productgridview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
after i pass the value i want to use it in this part of my php code
$cid = "CID value here from java";
here is the complete php code..
products.php
<?php
include('dbconnection.php');
$cid = "CID value here from java";
$statement = mysqli_query($con, "SELECT p.products_id, pd.products_name, p.products_price, p.products_image FROM products p INNER JOIN products_description pd ON p.products_id=pd.products_id WHERE p.products_status='1' ORDER BY p.products_sort_order ASC");
$products = array();
while($row = mysqli_fetch_array($statement)){
array_push($products,
array(
'products_id'=>$row[0],
'products_name'=>$row[1],
'products_price'=>$row[2],
'products_image'=>"http://joehamirbalabadan.com/android/images/".$row[3]
));
}
echo json_encode(array("products"=>$products));
mysqli_close($con);
?>
help me to construct my code.. thanks..
use following code for add parameters into http post request.I hope it will help you..!
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("cid", "testid"));
nameValuePair.add(new BasicNameValuePair("test", "testvalue"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
// finally make POST request.