I am working with an application where i get records from my azure database and insert it into an array, and the listview must display my array. My error comes when i try to call the method notifyDatasetChanged, Here is my code:
Button search;
EditText Esearch;
ListView list;
BaseAdapter ADAhere;
Connection connect;
List<Map<String,String>> MyData = new ArrayList();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.srail, container, false);
search = (Button)rootView.findViewById(R.id.btnSearch);
Esearch = (EditText)rootView.findViewById(R.id.srch);
list = (ListView)rootView.findViewById(R.id.view);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckLogin checkLogin = new CheckLogin();
checkLogin.execute("");
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_products, fromwhere, viewswhere);
list.setAdapter(ADAhere);
}
});
return rootView;
}
public class CheckLogin extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(getActivity(), "Searching...",
"Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String r) {
progress.dismiss();
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
if (isSuccess) {
Toast.makeText(getActivity(), "Search Successfull", Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... strings) {
String Search = search.getText().toString();
try {
ConnectionHelper conStr = new ConnectionHelper();
connect = conStr.connectionclass(); // Connect to database
if (connect == null) {
z = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail where rail_name='" + Search.toString() +"' ";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("NAME", rs.getString("RAIL_NAME"));
datanum.put("PRICE", rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE", rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER", rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE", rs.getString("RAIL_SIZE"));
MyData.add(datanum);
}
ADAhere.notifyDatasetChanged();
z = " successful";
isSuccess = true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
return z;
}
}
The Error comes in this portion of the code:
String query = "select * from cc_rail where rail_name='" + Search.toString() +"' ";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("NAME", rs.getString("RAIL_NAME"));
datanum.put("PRICE", rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE", rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER", rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE", rs.getString("RAIL_SIZE"));
MyData.add(datanum);
}
ADAhere.notifyDatasetChanged();
write
ADAhere.notifyDataSetChanged();
instead of
ADAhere.notifyDatasetChanged();
You wrote small s instead of S
This is more better practice to write this code in onPostExecute instead of writing this is doInBackground
Your problem is with the way you write the method name notifyDataSetChanged() (you used a small s in set), so it's normal that it does not recognize it
Change this line
ADAhere.notifyDatasetChanged();
with
ADAhere.notifyDataSetChanged();
You have created BaseAdapter and trying to notify the adapter. Create an ADAhere object as a SimpleAdapter which extends BaseAdapter
Related
Here I am sending data from local data base to mysql database server but aly first row data is uploading
Can anyone help me
here i am fetching data from sqlite using model class and display in recyclerview
now i want to send all recyclerview data in ARRAY or any other way to server database
Here 6 images are fetch from sqlite also send to server without setImage in UI directly want to send to Server
Thanks in advance....!!!
Activity Code
public class FetchLocalInsuranceListActivity extends AppCompatActivity {
protected ViewDialog viewDialog;
private RecyclerView recyclerview;
RequestQueue requestQueue;
private MyCustomAdapter myCustomAdapter;
Context context;
DatabaseHelper database;
List<DataModel> datamodel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fetch_local_insurance_list);
context = this;
datamodel = new ArrayList<DataModel>();
viewDialog = new ViewDialog(this);
viewDialog.setCancelable(false);
database = new DatabaseHelper(context);
datamodel = database.getAllSyncData();
recyclerview = (RecyclerView) findViewById(R.id.recycler_view__local_my_insurance);
LinearLayoutManager layoutManager = new LinearLayoutManager(FetchLocalInsuranceListActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
private List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView farmer_name, tv_Tagging_Date, tv_insurance_id;
protected ImageButton editButton;
public MyViewHolder(View view) {
super(view);
farmer_name = view.findViewById(R.id.text_insured_name);
tv_Tagging_Date = view.findViewById(R.id.tv_Tagging_Date);
tv_insurance_id = view.findViewById(R.id.tv_insurance_id);
editButton = itemView.findViewById(R.id.edit_button);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_local_insurance_list, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(MyCustomAdapter.MyViewHolder holder, final int position) {
final DataModel datum = moviesList.get(position);
Log.e("image", datum.getAnimal_Tail_Photo() + "");
holder.farmer_name.setText("Farmer Name : " + datum.getFarmer_name() + "");
holder.tv_Tagging_Date.setText("Tagging Date : " + datum.getTagging_date() + "");
holder.tv_insurance_id.setText("#SNV_INSURANCE_" + datum.getId() + " ");
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editDataParticularRow(datum);
}
});
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
private void editDataParticularRow(DataModel dataModel) {
Intent intent = new Intent(FetchLocalInsuranceListActivity.this, EditBankAndFarmerActivity.class);
intent.putExtra("BANK_ID", dataModel.getId() + "");
Log.e("id", dataModel.getId() + "");
startActivity(intent);
}
protected final void hideProgressDialog() {
viewDialog.dismiss();
}
protected void showProgressDialog() {
viewDialog.show();
}
protected void showProgressDialog(String message) {
showProgressDialog();
}
public void doNormalPostOperation(final int i) {
requestQueue = Volley.newRequestQueue(FetchLocalInsuranceListActivity.this);
final ProgressDialog progressDialog = new ProgressDialog(FetchLocalInsuranceListActivity.this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://thelastoffers.com/snv/webservices/test.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
database.deleteData(Integer.parseInt(datamodel.get(i).getId() + ""));
database.deleteAnimalData(Integer.parseInt(datamodel.get(i).getFarmer_id() + ""));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FetchLocalInsuranceListActivity.this, "Something went Wrong.. Please Try again..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
// params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
// REMAINING PARAMS WITH SAME datamodel.get(i) item
params.put("type", "insertOfflineData");
params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
params.put("head_image_blob", String.valueOf(datamodel.get(i).getAnimal_Tag_Photo()));
params.put("farmer_bank_hypo", datamodel.get(i).getFarmer_bank_hypo() + "");
params.put("farmer_name", datamodel.get(i).getFarmer_name() + "");
params.put("farmer_village", datamodel.get(i).getVillage() + "");
params.put("farmer_taluka", datamodel.get(i).getTaluka() + "");
params.put("farmer_district", datamodel.get(i).getDistrict() + "");
params.put("tagging_date", datamodel.get(i).getTagging_date() + "");
Log.e("Data", params + "");
return params;
}
};
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.sync_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sync:
for (int i = 0; i < datamodel.size(); i++) {
doNormalPostOperation(i);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
Database Code
public List<DataModel> getAllSyncData() {
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM FARMER_SYNC_TABLE LEFT JOIN ANIMAL_SYNC_TABLE ON farmer_id = new_insurane_id ORDER BY new_insurane_id DESC";
Cursor cursor = db.rawQuery(query, null);
Log.e("value", query + ";" + " ");
StringBuilder stringBuffer = new StringBuilder();
if (cursor.moveToFirst()) {
do {
DataModel dataModel_1 = new DataModel();
int NEW_INSURANCE_ID_1 = cursor.getInt(cursor.getColumnIndexOrThrow("new_insurane_id"));
String INSURANCE_ID_1 = cursor.getString(cursor.getColumnIndexOrThrow("insurance_id"));
String INSURED_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("insured_name"));
String BANKHYPO_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("bankhypo_name"));
String FARMER_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("farmer_name"));
String VILLAGE_1 = cursor.getString(cursor.getColumnIndexOrThrow("village"));
String TALUKA_1 = cursor.getString(cursor.getColumnIndexOrThrow("taluka"));
String DISTRICT_1 = cursor.getString(cursor.getColumnIndexOrThrow("district"));
String TAGGING_DATE_1 = cursor.getString(cursor.getColumnIndexOrThrow("tagging_date"));
int NEW_ANIMAL_ID = cursor.getInt(cursor.getColumnIndexOrThrow("new_animal_id"));
int FARMER_ID_1 = cursor.getInt(cursor.getColumnIndexOrThrow("farmer_id"));
String TAG_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("tag_no"));
String ANIMAL_EAR_POSITION_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_ear_position"));
String ANIMAL_SPECIES_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_species"));
String ANIMAL_BREED_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_breed"));
String ANIMAL_BODY_COLOR_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_body_color"));
String ANIMAL_SHAPE_RIGHT_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_shape_right"));
String ANIMAL_SHAPE_LEFT_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_shape_left"));
String ANIMAL_SWITCH_OF_TAIL_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_sitch_of_tail"));
String AGE_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("age_years"));
String ANIMAL_OTHER_MARKS_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_other_marks"));
String PRAG_STATUS_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("prag_status"));
String NUMBER_OF_LACTATION_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("number_of_lactation"));
String CURRENT_MILK_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("current_milk"));
String SUM_INSURED_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("sum_insured"));
dataModel_1.setId(NEW_INSURANCE_ID_1);
dataModel_1.setINSURANCE_ID(INSURANCE_ID_1);
dataModel_1.setFarmer_insure_name(INSURED_NAME_1);
dataModel_1.setFarmer_bank_hypo(BANKHYPO_NAME_1);
dataModel_1.setFarmer_name(FARMER_NAME_1);
dataModel_1.setVillage(VILLAGE_1);
dataModel_1.setTaluka(TALUKA_1);
dataModel_1.setDistrict(DISTRICT_1);
dataModel_1.setTagging_date(TAGGING_DATE_1);
dataModel_1.setAnimal_id(NEW_ANIMAL_ID);
dataModel_1.setFarmer_id(FARMER_ID_1);
dataModel_1.setTag_no(TAG_COLUMN_1);
dataModel_1.setEar_position(ANIMAL_EAR_POSITION_COLUMN_1);
dataModel_1.setAnimal_species(ANIMAL_SPECIES_COLUMN_1);
dataModel_1.setAnimal_breed(ANIMAL_BREED_COLUMN_1);
dataModel_1.setBody_color(ANIMAL_BODY_COLOR_COLUMN_1);
dataModel_1.setShape_right(ANIMAL_SHAPE_RIGHT_COLUMN_1);
dataModel_1.setShape_left(ANIMAL_SHAPE_LEFT_COLUMN_1);
dataModel_1.setTail_switch(ANIMAL_SWITCH_OF_TAIL_COLUMN_1);
dataModel_1.setAge(AGE_COLUMN_1);
dataModel_1.setOther_marks(ANIMAL_OTHER_MARKS_COLUMN_1);
dataModel_1.setPrag_status(PRAG_STATUS_COLUMN_1);
dataModel_1.setLactations(NUMBER_OF_LACTATION_COLUMN_1);
dataModel_1.setMilk_qty(CURRENT_MILK_COLUMN_1);
dataModel_1.setSum_insured(SUM_INSURED_COLUMN_1);
dataModel_1.setAnimal_Tag_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("tag_image"))));
dataModel_1.setAnimal_Head_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("head_image"))));
dataModel_1.setAnimal_Left_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("left_side_image"))));
dataModel_1.setAnimal_Right_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("right_side_image"))));
dataModel_1.setAnimal_Tail_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("tail_image"))));
dataModel_1.setAnimal_Farmer_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("farmer_image"))));
stringBuffer.append(dataModel_1);
data.add(dataModel_1);
} while (cursor.moveToNext());
}
db.close();
return data;
}
This is a simple problem. You are only using
use for loop to iterate through all items like,
for(int i=0; i<datamodel.size(); i++){
doNormalPostOperation(i)
}
and in doNormalPostOperation method
public void doNormalPostOperation(int i) {
// PREVIOUS CODE
#Override
protected Map<String, String> getParams() {
params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
// REMAINING PARAMS WITH SAME datamodel.get(i) item
}
}
which is causing that issue and only sending first item. You will need to iterate through all items to generate parameters and send to server, or else you can combine them to one json array and modify the code server side.
First you collect the Data from sqltables
/* Collecting Information */
public Cursor getAllData() {
String selectQuery = "Select * from "+TABLE_MEMBER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
public JSONObject createJsonObject(){
Cursor cursor = getAllData();
JSONObject jobj ;
JSONArray arr = new JSONArray();
cursor.moveToFIrst();
while(cursor.moveToNext()) {
jobj = new JSONObject();
jboj.put("Id", cursor.getInt("Id"));
jboj.put("Name", cursor.getString("Name"));
arr.put(jobj);
}
jobj = new JSONObject();
jobj.put("data", arr);
}
public void postJsonToServer(){
JSONObject js = createJsonObject();
String url = "YOUR -- Post Url";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
}
You can go through this:
Get all the data which you want to send, via select query and store this data in a array list.
Using GSON library you can convert that arraylist into json data
Now you have to create an API which receive that json data and parse it and insert every record to database.
On the app end you have to hit that API and pass json data to it.
I am creating a listview where i get my items from my azure database through an SQL query with a where statement. My code runs but when i try to search something a toast shows at the bottom of my screen with [], Here is my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.srail, container, false);
search = (Button)rootView.findViewById(R.id.btnSearch);
Esearch = (EditText)rootView.findViewById(R.id.srch);
list = (ListView)rootView.findViewById(R.id.raill);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckLogin checkLogin = new CheckLogin();
checkLogin.execute("");
List<Map<String,String>> MyData = new ArrayList();
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_products, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,Object> obj=(HashMap<String,Object>)ADAhere.getItem(position);
String ID=(String)obj.get("A");
Toast.makeText(getActivity(), ID, Toast.LENGTH_SHORT).show();
}
});
}
});
return rootView;
}
public class CheckLogin extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(getActivity(), "Searching...",
"Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String r) {
progress.dismiss();
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
if (isSuccess) {
Toast.makeText(getActivity(), "Search Successfull", Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... strings) {
String Search = search.getText().toString();
if (Search.trim().equals(""))
z = "Please Search something";
else {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
ConnectionHelper conStr = new ConnectionHelper();
connect = conStr.connectionclass(); // Connect to database
if (connect == null) {
z = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail where rail_name='" + Search.toString() + "' OR RAIL_UNIT_PRICE= '" + Search.toString() + "' OR RAIL_RANGE= '" + Search.toString() + "' OR RAIL_SUPPLIER='" + Search.toString() + "' OR RAIL_SIZE='" + Search.toString() + "'";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("NAME", rs.getString("RAIL_NAME"));
datanum.put("PRICE", rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE", rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER", rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE", rs.getString("RAIL_SIZE"));
data.add(datanum);
}
z = " successful";
isSuccess = true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
return String.valueOf(data);
}
return z;
}
}
}
You're using this MyData variable as the data source for you adapter:
List<Map<String,String>> MyData = new ArrayList();
...
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_products, fromwhere, viewswhere);
...
list.setAdapter(ADAhere);
And yet you're not adding anything neither to the direct data source MyData nor through the adapter ADAhere.
EDIT:
What you can do to fix this is, make your data variable global (move it to before onCreateView():
List<Map<String,String>> MyData = new ArrayList();
Then inside your asynctask you call add to add data to it:
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("NAME", rs.getString("RAIL_NAME"));
datanum.put("PRICE", rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE", rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER", rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE", rs.getString("RAIL_SIZE"));
MyData.add(datanum);
}
ADAhere.notifyDatasetChanged()
Then simply call ADAhere.notifyDatasetChanged() when you're done loading data into MyData.
I have my class that is based on a tutorial online, i dont fully understand it yet ( working on it ), but its working.
It populates the listview, now i want to get the id and show the data related to that id on a more detailed activity.
I already obtain the id of the item i am clicking:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
But now, i am not getting how i will do this, get the data of the position i clicked.
I have a inner class "GetObras" but i cant use the variables from it on my onCreate, i tried make them global, etc
public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener{
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView list;
private static String url = "http://ploran.gear.host/scriptobras6.php";
ArrayList<HashMap<String, String>> obrasList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obrasList = new ArrayList<HashMap<String, String>>();
list = (ListView)findViewById(R.id.list1);
new GetObras().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
}
private class GetObras extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray obras = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray obras = jsonObj.getJSONArray("obras");
// looping through All
for (int i = 0; i < obras.length(); i++) {
JSONObject c = obras.getJSONObject(i);
String id = c.getString("Id");
String nomeObra = c.getString("NomeObra");
String idCliente = c.getString("idCliente");
String DataLevantamento = c.getString("DataPLevantamento");
String DataRealizacao = c.getString("DataRLevantamento");
String Estado = c.getString("Estado");
String DataMateriais = c.getString("DataRMateriais");
String DataInicioObra = c.getString("DataInicioObra");
String DataConclusao = c.getString("DataConclusao");
String DataVestoria = c.getString("DataVestoria");
String Obs = c.getString("Obs");
String Prompor = c.getString("Prompor");
String Levantpor = c.getString("Levantpor");
String executpor = c.getString("executpor");
// tmp hash map for single contact
HashMap<String, String> obra = new HashMap<>();
// adding each child node to HashMap key => value
obra.put("Id", id);
obra.put("nomeObra", nomeObra);
obra.put("idCliente", idCliente);
obra.put("DataLevantamento", DataLevantamento);
obra.put("DataRealizacao", DataRealizacao);
obra.put("Estado", Estado);
obra.put("DataMateriais", DataMateriais);
obra.put("DataIncioObra", DataInicioObra);
obra.put("DataConclusao", DataConclusao);
obra.put("DataVestoria", DataVestoria);
obra.put("Obs", Obs);
obra.put("Prompor", Prompor);
obra.put("Levantpor", Levantpor);
obra.put("executpor", executpor);
// adding contact to contact list
obrasList.add(obra);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, obrasList,
R.layout.list_item, new String[]{"nomeObra", "idCliente",
"Estado"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
list.setAdapter(adapter);
}
}
List<String> cities;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// User pressed the search button
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// User changed the text
return false;
}
}
If what i think is correct, i could just get the JsonArray from the doInBackground method in GetObras and do:
JSONObject c = obras.getJSONObject(position);
Thank you.
You can retrieve it using obrasList reference. As your are passing obrasList to your adapter.
Below is the sample code:
obrasList.get(position).get(yourkey);
Hope this will help you.. :))
I have been having a problem lately, I have successfully created a listview in the FillList method that displays the items that i need. That is all well. The problem is how do I convert it to a multi-select checkbox like style so that when I select an item it will just be stored in an array for later use. Any insight is helpful.
Here is my PathfinderUpdate.java:
public class PathfinderUpdate extends Fragment {
ConnectionClass connectionClass;
EditText edtproname, edtprodesc;
Button btnadd,btnupdate,btndelete,btnrefresh;
ProgressBar pbbar;
ListView lstpro;
String pathid;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.update_pathfinder, container, false);
connectionClass = new ConnectionClass();
btnupdate = (Button) rootView.findViewById(R.id.btnupdate);
lstpro = (ListView) rootView.findViewById(R.id.lstproducts);
btnrefresh = (Button) rootView.findViewById(R.id.btnrefresh);
pathid = "";
FillList fillList = new FillList();
fillList.execute("");
btnrefresh.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
FillList Fill = new FillList();
Fill.execute("");
}
});
return rootView;
}
#Override
public void onResume(){
super.onResume();
FillList Fill = new FillList();
Fill.execute("");
}
public class FillList extends AsyncTask<String, String, String> {
String z = "";
List<Map<String, String>> prolist = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute() {
//old pbbar
}
#Override
protected void onPostExecute(String r) {
String[] from = { "pathfinder_id", "pathfinder_name"};
int[] views = { R.id.lblproid, R.id.lblproname };
final SimpleAdapter ADA = new SimpleAdapter(getActivity(),
prolist, R.layout.lsttemplate, from,views);
lstpro.setAdapter(ADA);
lstpro.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
#SuppressWarnings("unchecked")
HashMap<String, Object> obj = (HashMap<String, Object>) ADA
.getItem(arg2);
pathid = (String) obj.get("pathfinder_id");
String idea_name = (String) obj.get("pathfinder_name");
String benefit_eqv = (String) obj.get("pathfinder_eqv");
String quickwin = (String) obj.get("pathfinder_quick");
String observe = (String) obj.get("pathfinder_obs");
String ideaId = (String) obj.get("pathfinder_idea_id");
String BenefitId = (String) obj.get("pathfinder_benefit");
String closure = (String) obj.get("pathfinder_closure");
Integer ideaIdMain = Integer.parseInt(ideaId);
Integer benefitIdMain = Integer.parseInt(BenefitId);
Integer pathfinderId = Integer.parseInt(pathid);
Double benefiteqv = Double.parseDouble(benefit_eqv);
Bundle bundle = new Bundle();
bundle.putString("id2", pathid);
bundle.putString("name", idea_name);
bundle.putDouble("eqv", benefiteqv);
bundle.putString("quick", quickwin);
bundle.putString("observation", observe);
bundle.putInt("idea_id", ideaIdMain);
bundle.putInt("benefit_id", benefitIdMain);
bundle.putString("closure", closure);
bundle.putInt("id", pathfinderId);
Intent updateMain = new Intent(getActivity(), PathfinderUpdateMain.class);
updateMain.putExtras(bundle);
startActivity(updateMain);
// qty.setText(qtys);
}
});
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from pathfinder ORDER BY pathfinder_id ASC";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("pathfinder_id", rs.getString("pathfinder_id"));
datanum.put("pathfinder_name", rs.getString("pathfinder_name"));
datanum.put("pathfinder_status", rs.getString("pathfinder_status"));
datanum.put("pathfinder_eqv", rs.getString("pathfinder_potential_eqv"));
datanum.put("pathfinder_obs", rs.getString("pathfinder_observation"));
datanum.put("pathfinder_quick", rs.getString("pathfinder_quickwin"));
datanum.put("pathfinder_idea_id", rs.getString("idea_id"));
datanum.put("pathfinder_benefit", rs.getString("benefit_id"));
datanum.put("pathfinder_closure", rs.getString("pathfinder_target_closure"));
prolist.add(datanum);
}
z = "Success";
}
} catch (Exception ex) {
z = "Error retrieving data from table";
Log.e("MYAPP", "exception", ex);
}
return z;
}
}
}
Check this out i believe its much more close to the new design guidelines!!!
You can create your own adapter and customise list item.
here is a tutorial about list view.
for your questions. chapter 15 might be what you have been looking for.
http://www.vogella.com/tutorials/AndroidListView/article.html#listview_selection
hope this help !!!
I would like to display the data from MySql in a listview using a search parameter in my application.
I've succeeded, but the problem I'm having is that every time I push the search button twice, both sets of result data are shown in the ListView, whereas I only want to display the latest set of results.
This is the code I'm using:
public class ListPerusahaan extends ListActivity {
/** Called when the activity is first created. */
private static final String TAG_ID = "id";
private static final String TAG_NAMA = "nama_perusahaan";
private static final String TAG_PEKERJAAN = "pekerjaan";
private static final String TAG_ALAMAT= "alamat";
private static final String TAG_DEADLINE = "deadline";
EditText keyword; Button search; private ProgressDialog pDialog; ArrayList<HashMap<String, String>> DataList; // JSONArray perusahaan = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listperusahaan);
keyword=(EditText)findViewById(R.id.Editsearch);
search=(Button)findViewById(R.id.search);
DataList = new ArrayList<HashMap<String, String>>();
search.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v) {
// TODO Auto-generated method stub
if (keyword.getText().toString().length() == 0 ) {
Toast toast = Toast.makeText(getApplicationContext(),"Please enter your keyword", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else {
new searchData().execute();
}
}
});
}
#SuppressLint("NewApi") public class searchData extends AsyncTask<Void, Void, Void>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListPerusahaan.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> paramemeter = new ArrayList<NameValuePair>();
paramemeter.add(new BasicNameValuePair("keyword", keyword.getText().toString()));
JSONObject json = JSONParser.getJSONFromUrl("http://10.0.2.2/appmysql/dataperusahaan.php", paramemeter);
try{
JSONArray perusahaan = json.getJSONArray("perusahaan");
if (perusahaan != null)
{
for(int i=0;i<perusahaan.length();i++){
// HashMap<String, String> map1 = new HashMap<String, String>();
JSONObject jsonobj = perusahaan.getJSONObject(i);
// Storing each json item in variable
String id = jsonobj.getString(TAG_ID);
String nama_perusahaan = jsonobj.getString(TAG_NAMA);
String pekerjaan = jsonobj.getString(TAG_PEKERJAAN);
String alamat = jsonobj.getString(TAG_ALAMAT);
String deadline = jsonobj.getString(TAG_DEADLINE);
// creating new HashMap
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put(TAG_ID, id);
map1.put(TAG_NAMA, nama_perusahaan);
map1.put(TAG_PEKERJAAN, pekerjaan);
map1.put(TAG_ALAMAT, alamat);
map1.put(TAG_DEADLINE, deadline);
// adding HashList to ArrayList
DataList.add(map1);
}
}
else {
Toast toast= Toast.makeText(getApplicationContext(), "No data found", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
catch(JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ListPerusahaan.this, DataList,R.layout.row,
new String[] { TAG_NAMA, TAG_PEKERJAAN, TAG_ALAMAT, TAG_DEADLINE },
new int[] { R.id.nama_perusahaan, R.id.pekerjaan, R.id.alamat,R.id.deadline});
// updating listview
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(ListPerusahaan.this, "Perusahaan '" + o.get("nama_perusahaan") + "' was clicked.", Toast.LENGTH_SHORT).show();
*/
// getting values from selected ListItem
String nama = ((TextView) view.findViewById(R.id.nama_perusahaan)).getText().toString();
String pekerjaan = ((TextView) view.findViewById(R.id.pekerjaan)).getText().toString();
String alamat = ((TextView) view.findViewById(R.id.alamat)).getText().toString();
String deadline = ((TextView) view.findViewById(R.id.deadline)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), detail_lowongan.class);
in.putExtra(TAG_NAMA, nama);
in.putExtra(TAG_PEKERJAAN, pekerjaan);
in.putExtra(TAG_ALAMAT, alamat);
in.putExtra(TAG_DEADLINE, deadline);
startActivity(in);
}
});
}
});
}
}
}
Edit: in onclick clear DataList
search.setOnClickListener(){
......
DataList.clear(); //in onclick method
}
I am not sure whether you are looking for this or not...but if you don't want to allow duplicates in your list try ....
When the data filled in your list
Set<type> set=new Hashset(yourlist);
ArrayList<type> nodupList=new ArrayList<type>();
noduplist.addAll(set);
using this way it will remove the duplicates in your list
Edit:
Try this
After for loop
Set<HashMap> set=new HashSet(DataList);
ArrayList<HashMap> nodupList=new ArrayList<HashMap>();
nodupList.addAll(set);
DataList.clear();
DataList.addAll(nodupList);
try it may help you
Clear the DataList of the ArrayList type before populating it in the for loop.