Check box sending value to next activity even after deselcting it - android

I used a listview to display the check boxes in my activity. I also put a check to see atleast one check box is checked otherwise it will toast a message asking the user to please select atleast one value. Below are my two classes. Problem which i am having is that when i press the submit button without selecting a check box then i get a message to select atleast one checkbox. But when i select and deselect the check box and then submit it then it goes to the next activity with value of the check box which i dont want. It should not go to the other activity till i select one checkbox. Please help me with this problem.
ConnectAdapter.java
package com.arcadian.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.arcadian.genconian.R;
public class ConnectAdapter extends ArrayAdapter<ConnectModel> {
public ArrayList<ConnectModel> stateList;
Context cntx;
public static ConnectModel connect;
CheckBox cb;
public ConnectAdapter(Context context, int textViewResourceId,
ArrayList<ConnectModel> stateList) {
super(context, textViewResourceId, stateList);
this.cntx = context;
this.stateList = new ArrayList<ConnectModel>();
this.stateList.addAll(stateList);
}
public class ViewHolder {
CheckBox connect_CB;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) cntx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_connect_row, null);
holder = new ViewHolder();
holder.connect_CB = (CheckBox) convertView
.findViewById(R.id.connect_CB);
convertView.setTag(holder);
holder.connect_CB
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton v,
boolean isChecked) {
// TODO Auto-generated method stub
cb = (CheckBox) v;
if (v.isChecked()) {
connect = (ConnectModel) cb.getTag();
/*
* Toast.makeText( cntx.getApplicationContext(),
* "Checkbox: " + cb.getText() + " -> " +
* cb.isChecked(), Toast.LENGTH_LONG).show();
*/
connect.setSelected(cb.isChecked());
}
// else{
// Toast.makeText(getContext(), "Select aleast one.", Toast.LENGTH_LONG).show();
// String select = null;
// }
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
ConnectModel state = stateList.get(position);
holder.connect_CB.setText(state.getName());
holder.connect_CB.setChecked(state.isSelected());
holder.connect_CB.setTag(state);
return convertView;
}
}
**ConnectActivity.java**
package com.arcadian.genconian;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.arcadian.adapter.ConnectAdapter;
import com.arcadian.adapter.ConnectModel;
import com.arcadian.utils.CommonActivity;
import com.arcadian.utils.Constants;
import com.arcadian.utils.JSONParser;
public class ConnectActivity extends CommonActivity implements OnClickListener {
ConnectAdapter dataAdapter = null;
ArrayList<ConnectModel> stateList;
private ProgressDialog pDialog;
String to_connect;
String response;
private StringBuffer responseText;
int success;
String email, type;
private String status;
String select;
ConnectModel _ConnectModel;
ConnectModel selstate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// Generate list View from ArrayList
displayListView();
responseText = new StringBuffer();
Button submit_BT = (Button) findViewById(R.id.submit_BT);
submit_BT.setOnClickListener(this);
Intent i = getIntent();
email = i.getStringExtra("user_email");
type = i.getStringExtra("type");
}
private void displayListView() {
// Array list of countries
stateList = new ArrayList<ConnectModel>();
_ConnectModel = new ConnectModel("All", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Stream", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Industry", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Field", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Batchmates", false);
stateList.add(_ConnectModel);
// create an ArrayAdaptar from the String Array
dataAdapter = new ConnectAdapter(this, android.R.layout.simple_list_item_multiple_choice,
stateList);
ListView to_connect_LV = (ListView) findViewById(R.id.to_connect_LV);
// Assign adapter to ListView
to_connect_LV.setAdapter(dataAdapter);
}
#Override
public void onClick(View v) {
int id = v.getId();
// openRequest.setCallback(statusCallback);
// session.openForRead(openRequest);
// loginProgress.setVisibility(View.VISIBLE);
switch (id) {
case R.id.submit_BT:
ArrayList<ConnectModel> stateList = dataAdapter.stateList;
response = "";
for (int i = 0; i < stateList.size(); i++) {
ConnectModel state = stateList.get(i);
selstate = ConnectAdapter.connect;
if(selstate!=null)
if (selstate.equals(state)) {
select = "abc";
if ((stateList.size() - 1) >= i) {
responseText.append(state.getName() + ",");
String text = state.getName();
response = responseText.toString();
loge("response", "response text is" + responseText);
}
else {
responseText.append(state.getName());
}
}
}
if (select == null) {
Toast.makeText(getApplicationContext(), "Select at least one.",
Toast.LENGTH_SHORT).show();
} else {
new Connect().execute();
}
/*
* if(response.length()>1) {
* if(response.substring(response.length()-1).equals(",") ) {
* response
* =response.replace(response.substring(response.length()-1), "" );
*
* }
*
* }
*
* if (response.length() <= 1) { response =
* "batch,stream,field,industry"; }
*/
break;
default:
break;
}
}
public class Connect extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConnectActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
to_connect = responseText.toString();
String connect_url = Constants.REMOTE_URL + "/GenconianApi/reg2";
log("to", "connect url is:" + connect_url);
try {
JSONParser jsonParser = new JSONParser();
List<NameValuePair> Params = new ArrayList<NameValuePair>();
String res;
Intent email_Intent = getIntent();
email = email_Intent.getStringExtra("user_email");
type = email_Intent.getStringExtra("type");
loge("email in", "connectactivity is:" + email);
int len = response.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < len - 1; i++) {
builder.append(Character.toLowerCase(response.charAt(i)));
}
Params.add(new BasicNameValuePair("email", email));
Params.add(new BasicNameValuePair("connected", builder
.toString()));
Log.e("responce", builder.toString());
JSONObject json = jsonParser.makeHttpRequest(connect_url,
"POST", Params);
loge("in reg2", json.toString());
JSONObject obj = json.getJSONObject("Status");
loge("obj is", obj.toString());
status = obj.getString("status");
loge("user", "status is:" + status);
success = Integer.parseInt(status);
loge("chk", "rslt code is:" + success);
if (success == 1) {
Intent k = new Intent(ConnectActivity.this,
FindFriends.class);
loge("chk", "inside success:" + success);
k.putExtra("user_email", email);
k.putExtra("type", type);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
startActivity(k);
loge("email", "" + email);
return json.getString(Constants.TAG_MESSAGE);
} else {
Log.e("Login Failure!",
json.getString(Constants.TAG_MESSAGE));
return json.getString(Constants.TAG_MESSAGE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i = new Intent(ConnectActivity.this, More.class);
i.putExtra("user-email", email);
i.putExtra("type", type);
startActivity(i);
}
}

You can put all the checkboxes in a Collection of checkboxes.
Upon clicking submit button, loop through all checkboxes to see anyone of them is checked at that moment
Collection<CheckBox> boxes=new Vector<CheckBox>();
...
public void onClick(View v){
boolean anyoneChecked=false;
for(CheckBox b: boxes){
if(b.isChecked()){
anyoneChecked=true;
}
}
if(!anyoneChecked){
return;
}
// go to next activity
}

Related

Trigger an event when i return to an Event

Im trying to trigger an event when i return to an activity hitting the back button.
what i want to do is when i go back with the backbutton reload some items. Is there any way to do this?
here is my Main Activity where i want to do the "reload" of data, Some thing like "onResume" or "onReEnter"
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ActivityTemporadaJson extends AppCompatActivity {
private String Nombre;
private int IdTmdb;
private String Tipo;
private int NumeroTemp;
private DBHelper mydb;
private ProgressDialog pDialog;
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original";
private Temporada temp;
private TextView nombrePelicula;
private ImageView fotoPortada;
private TextView sinopsis;
private TextView NumEpsVal;
private TextView fechaLanzVal;
private ArrayList<Episodio> episodios;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private RecyclerAdapterEpisodio mAdapterEp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temporada_json);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent recep = this.getIntent();
episodios = new ArrayList<>();
Nombre = recep.getStringExtra("Nombre");
Tipo = recep.getStringExtra("Tipo");
IdTmdb = Integer.parseInt(recep.getStringExtra("idSerie"));
NumeroTemp = Integer.parseInt(recep.getStringExtra("NumTemp"));
this.setTitle(Nombre);
nombrePelicula = (TextView) this.findViewById(R.id.NombrePelicula);
fotoPortada = (ImageView) this.findViewById(R.id.FotoPortada);
sinopsis = (TextView) this.findViewById(R.id.Sinopsis);
NumEpsVal = (TextView) this.findViewById(R.id.NumEpsVal);
fechaLanzVal = (TextView) this.findViewById(R.id.FechaLanzVal);
recyclerView = (RecyclerView) this.findViewById(R.id.recyclerviewEpisodios);
mydb = new DBHelper(this);
if (Tipo.equalsIgnoreCase("SQL")) {
Cursor res = mydb.getResultQuery("SELECT count(e.Visto) as numVisto FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp + " and e.visto = 1");
res.moveToFirst();
int NumVisto = res.getInt(0);
mydb.UpdateEpsVistos(NumVisto, IdTmdb, NumeroTemp);
TextView NumEpsVis = (TextView) this.findViewById(R.id.EpsVis);
TextView NumEpsVisVal = (TextView) this.findViewById(R.id.EpsVisVal);
NumEpsVis.setVisibility(View.VISIBLE);
NumEpsVisVal.setVisibility(View.VISIBLE);
AQuery androidAQuery = new AQuery(this);
res = mydb.getResultQuery("SELECT Nombre, Sinopsis, FechaInicio, Poster, NumeroEpisodios,EpisodiosVistos FROM Temporada WHERE IdTMDB = " + IdTmdb + " and NumeroTemporada = " + NumeroTemp);
res.moveToFirst();
nombrePelicula.setText(res.getString(0));
sinopsis.setText(res.getString(1));
fechaLanzVal.setText(res.getString(2));
androidAQuery.id(fotoPortada).image(res.getString(3), true, true, 150, 0);
NumEpsVal.setText(Integer.toString(res.getInt(4)));
NumEpsVisVal.setText(Integer.toString(res.getInt(5)));
Cursor resEps = mydb.getResultQuery("SELECT e.Nombre, e.NumeroEpisodio, e.NumeroTemporada, e.FechaEmision, e.Sinopsis, e.Poster, e.Visto, e.IdEpisodio FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp);
resEps.moveToFirst();
while (resEps.isAfterLast() == false) {
boolean visto = false;
if (resEps.getInt(6) == 1) {
visto = true;
}
Episodio nuevo = new Episodio(resEps.getInt(7), 0, resEps.getString(0), resEps.getInt(1), resEps.getInt(2), resEps.getString(3), resEps.getString(4), resEps.getString(5), visto);
episodios.add(nuevo);
resEps.moveToNext();
}
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(episodios, IdTmdb, Tipo);
recyclerView.setAdapter(mAdapterEp);
} else {
new GetTemp(this).execute();
}
//mydb = new DBHelper(this);
}
private class GetTemp extends AsyncTask<Void, Void, Void> {
Context c;
public GetTemp(Context c)
{
this.c = c;
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
//https://api.themoviedb.org/3/tv/57243/season/1?api_key=5e2780b2117b40f9e4dfb96572a7bc4d&language=en-US
String url = "https://api.themoviedb.org/3/tv/"+IdTmdb+"/season/"+NumeroTemp+"?api_key="+API+"&language=es-ES";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray episodes = jsonObj.getJSONArray("episodes");
String fecha = jsonObj.getString("air_date");
String nombreSerie = jsonObj.getString("name");
int numEps = episodes.length();
int numTemp = jsonObj.getInt("season_number");
String sinop = jsonObj.getString("overview");
String poster =URLFOTO + jsonObj.getString("poster_path");
// looping through All Contacts
for (int i = 0; i < episodes.length(); i++) {
JSONObject c = episodes.getJSONObject(i);
Episodio nuevo = new Episodio();
nuevo.setSinopsis(c.getString("overview"));
nuevo.setFechaEmision(c.getString("air_date"));
nuevo.setNombreEpisodio(c.getString("name"));
nuevo.setNumeroEpisodio(c.getInt("episode_number"));
nuevo.setNumeroTemporada(c.getInt("season_number"));
nuevo.setPoster(URLFOTO + c.getString("still_path"));
episodios.add(nuevo);
}
temp = new Temporada(0, IdTmdb, nombreSerie, sinop, fecha, poster, numTemp,false, 0, numEps, episodios);
} catch (final JSONException e) {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
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);
AQuery androidAQuery=new AQuery(c);
// Dismiss the progress dialog
if (pDialog.isShowing())
{
pDialog.dismiss();
}
androidAQuery.id(fotoPortada).image(temp.getPoster(), true, true, 150,0);
String Nombre = "Temporada " + temp.getNumeroTemporada();
nombrePelicula.setText(Nombre);
sinopsis.setText(temp.getSinopsis());
NumEpsVal.setText(Integer.toString(temp.getNumeroEpisodios()));
fechaLanzVal.setText(temp.getFechaInicio());
mLinearLayoutManager = new LinearLayoutManager(c, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(temp.getEpisodios(),IdTmdb,Tipo);
recyclerView.setAdapter(mAdapterEp);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(c);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
}
You can use onRestart , which will be triggered when existing activity will be bought back to front .
As quoted in docs
Called after onStop() when the current activity is being re-displayed
to the user (the user has navigated back to it). It will be followed
by onStart() and then onResume().
so Override onRestart
#Override
public void onRestart() {
// you come back to me
}

How to get row wise increment in counter starting from one in each row listview

I want to count row wise total for each item according to its quantity.my problem is that i want to start increment in each row from 1 but if i do increment in first row for e.g. from 1 to 5 then in next row its start from 6 but I want it will start from 1.how I resolve this problem?
Code is:
OrderScreenActivity.java
package com.example.veer.quickpos.activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.veer.quickpos.R;
import com.example.veer.quickpos.adapter.ListAdapter;
import com.example.veer.quickpos.adapter.ListItemAdapter;
import com.example.veer.quickpos.utility.Utils;
import com.example.veer.quickpos.utils.app.Constants;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Veer on 12/07/2016.
*/
public class OrderScreenActivity extends BaseActivity {
public static String CmpId, GroupID, GroupName, UnderGroupId, ParentGroupName,ItemID,ItemName,CategoryID,SellingPrice;
public static ArrayList<String> CmpIdList, GroupIDList, GroupNameList, UnderGroupIdList, ParentGroupNameList;
public static LinearLayout ll;
public EditText edtitem;
public ListView lstitem;
public ListView listItemqty;
public static String item;
ListAdapter adapter;
public int total;
ListItemAdapter adapter2;
public static ArrayList<String> nameList,priceLIst,ItemIDList,ItemNameList,CategoryIDList,SellingPriceList,qtyList;
ProgressDialog pDialog;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
lstitem = (ListView)findViewById(R.id.lstitem);
edtitem = (EditText)findViewById(R.id.edtitem);
listItemqty = (ListView)findViewById(R.id.listviewItem);
makeJsonStringRequest();
}
public void makeJsonStringRequest() {
String URL = Utils.BASE_URL + Utils.GET_GROUP + Utils.AUTH_KEY;
Log.e("URL =>", URL);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.i("Response", response);
JSONArray mResponse = new JSONArray(response);
CmpIdList = new ArrayList<String>();
GroupIDList = new ArrayList<String>();
GroupNameList = new ArrayList<String>();
UnderGroupIdList = new ArrayList<String>();
ParentGroupNameList = new ArrayList<String>();
if (mResponse.length() != 0) {
for (int i = 0; i < mResponse.length(); i++) {
JSONObject obj = mResponse.optJSONObject(i);
CmpId = obj.optString("CmpId");
GroupID = obj.optString("GroupID");
GroupName = obj.optString("GroupName");
UnderGroupId = obj.optString("UnderGroupId");
ParentGroupName = obj.optString("ParentGroupName");
Log.d("CmpId", "" + CmpId);
Log.d("GroupID", "" + GroupID);
Log.d("GroupName", "" + GroupName);
Log.d("UnderGroupId", "" + UnderGroupId);
Log.d("ParentGroupName", "" + ParentGroupName);
CmpIdList.add(CmpId);
GroupIDList.add(GroupID);
GroupNameList.add(GroupName);
UnderGroupIdList.add(UnderGroupId);
ParentGroupNameList.add(ParentGroupName);
/*GetGodowns getGodowns = new GetGodowns();
getGodowns.setGoDownId(_id);
getGodowns.setName(_name);
getGodowns.setDate(CurrentDate);
getGodowns.setSyncData(_Sync);
listGetGodowns.add(getGodowns);*/
}
for (int i = 0; i < CmpIdList.size(); i++) {
ll = (LinearLayout) findViewById(R.id.llgroup);
ll.setOrientation(LinearLayout.HORIZONTAL);
Button txv = new Button(OrderScreenActivity.this);
txv.setWidth(290);
txv.setHeight(180);
txv.setTextColor(getResources().getColor(R.color.darksky));
txv.setText(GroupNameList.get(i));
ll.addView(txv);
txv.setTextSize(15);
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("in onclick:","");
item = edtitem.getText().toString();
Log.d("value of edittext text:",""+item);
makeJsonStringRequestItem(item);
}
});
Log.d("Id of textview :", "" + txv.getId());
}
//myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
hideProgress();
// myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
// hideProgress();
}
hideProgress();
Log.e(Constants.TAG, "GetTill response => " + mResponse.toString(4));
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgress();
Toast.makeText(OrderScreenActivity.this, "Error in fetching data, PLease try again", Toast.LENGTH_LONG).show();
Log.v("Error String Request", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
showProgress();
}
public void makeJsonStringRequestItem(String Item) {
Log.d("item group id in item api:",""+GroupID);
String URL = Utils.BASE_URL + Utils.GET_ITEMS + Utils.AUTH_KEY +"&ItemName="+ Item +"&GroupId=0";
Log.e("URL =>", URL);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.i("Response", response);
JSONArray mResponse = new JSONArray(response);
CmpIdList = new ArrayList<String>();
ItemIDList = new ArrayList<String>();
ItemNameList = new ArrayList<String>();
CategoryIDList = new ArrayList<String>();
SellingPriceList = new ArrayList<String>();
if (mResponse.length() != 0) {
for (int i = 0; i < mResponse.length(); i++) {
JSONObject obj = mResponse.optJSONObject(i);
CmpId = obj.optString("CmpId");
ItemID = obj.optString("ItemID");
ItemName = obj.optString("ItemName");
CategoryID = obj.optString("CategoryID");
SellingPrice = obj.optString("SellingPrice");
Log.d("CmpId", "" + CmpId);
Log.d("ItemID", "" + ItemID);
Log.d("ItemName", "" + ItemName);
Log.d("CategoryID", "" + CategoryID);
Log.d("SellingPrice", "" + SellingPrice);
CmpIdList.add(CmpId);
ItemIDList.add(ItemID);
ItemNameList.add(ItemName);
CategoryIDList.add(CategoryID);
SellingPriceList.add(SellingPrice);
/*GetGodowns getGodowns = new GetGodowns();
getGodowns.setGoDownId(_id);
getGodowns.setName(_name);
getGodowns.setDate(CurrentDate);
getGodowns.setSyncData(_Sync);
listGetGodowns.add(getGodowns);*/
}
Log.d("Itemnamelist value:",ItemNameList.toString());
Log.d("SellingPriceList value:",SellingPriceList.toString());
adapter = new ListAdapter(OrderScreenActivity.this,ItemNameList,SellingPriceList);
lstitem.setAdapter(adapter);
adapter2 = new ListItemAdapter(OrderScreenActivity.this,ItemNameList,SellingPriceList);
listItemqty.setAdapter(adapter2);
for (int i = 0; i < CmpIdList.size(); i++) {
ll = (LinearLayout) findViewById(R.id.llgroup);
ll.setOrientation(LinearLayout.HORIZONTAL);
Button txv = new Button(OrderScreenActivity.this);
txv.setWidth(290);
txv.setHeight(180);
txv.setTextColor(getResources().getColor(R.color.darksky));
txv.setText(GroupNameList.get(i));
ll.addView(txv);
txv.setTextSize(15);
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Log.d("Id of textview :", "" + txv.getId());
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
hideProgress();
// myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
// hideProgress();
}
hideProgress();
Log.e(Constants.TAG, "Getgroup item response => " + mResponse.toString(4));
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgress();
Toast.makeText(OrderScreenActivity.this, "Error in fetching data, PLease try again", Toast.LENGTH_LONG).show();
Log.v("Error String Request", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
showProgress();
}
private void showProgress() {
pDialog = new ProgressDialog(OrderScreenActivity.this);
pDialog.setMessage("Wait a moment");
pDialog.setCancelable(false);
pDialog.show();
}
private void hideProgress() {
if (null != pDialog) {
pDialog.dismiss();
}
}
}
ListItemAdapter
package com.example.veer.quickpos.adapter;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.veer.quickpos.R;
import java.util.ArrayList;
public class ListItemAdapter extends BaseAdapter {
Activity context;
public ArrayList<String> NameList;
public ArrayList<String> PriceList;
public ArrayList<String> totalList;
public int flag;
public static int qty;
public static ArrayList<String> qtyList;
public int total,grandtotal;
public ListItemAdapter(Activity a, ArrayList<String> nameList,ArrayList<String> plist) {
this.context = a;
this.NameList = nameList;
this.PriceList = plist;
}
/*private view holder class*/
class ViewHolder {
public TextView txtname,txtprice,txttotal;
public TextView txtqty;
public Button btnplus, btnminus;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_item_qty, null);
holder = new ViewHolder();
holder.btnplus = (Button) convertView.findViewById(R.id.btnplus);
holder.btnplus.setTag(position);
holder.btnminus = (Button) convertView.findViewById(R.id.btnminus);
holder.txtname = (TextView) convertView.findViewById(R.id.item);
holder.txtqty = (TextView) convertView.findViewById(R.id.itemqty);
holder.txtqty.setTag(R.id.itemqty,position);
holder.txtprice = (TextView) convertView.findViewById(R.id.txtprice);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
qtyList = new ArrayList<String>();
Log.d("Total row:",""+getCount());
Log.d("current position:",""+position);
Log.d("Item name at position:", "" + position + NameList.get(position));
holder.txtname.setText(NameList.get(position));
holder.txtprice.setText(PriceList.get(position));
holder.txtqty.setText(String.valueOf(flag));
// qty = Integer.parseInt(holder.txtqty.getText().toString());
// qtyList.add(String.valueOf(qty));
qty=1;
Log.d("value of qty before button plus click:",""+qty);
Log.d("value of flag before button plus click:",""+flag);
// final int pos=(Integer)convertView.getTag();
holder.btnplus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int total = 0;
flag = qty;
Log.d("value of flag in button plus :",""+flag);
int itempos = holder.txtqty.getId();
holder.txtqty.setText(String.valueOf(flag));
Log.d("value of textqty in button plus :",""+holder.txtqty.getText().toString());
int pos=(Integer)v.getTag();
total = total + (Integer.parseInt(PriceList.get(pos))* (Integer.parseInt(holder.txtqty.getText().toString())));
Log.d("value of total in button plus :",""+total);
flag++;
}
});
holder.btnminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(qty>0) {
qty = qty - 1;
Log.d("Value of qty in minus button:", "" + qty);
holder.txtqty.setText(String.valueOf(qty));
total = total + (Integer.parseInt(PriceList.get(position)) * (qty));
Log.d("total is:", "" + total);
}
}
});
return convertView;
}
#Override
public int getCount() {
return NameList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
}
In adapter I did code for counter in btnplus click event.I want to set qty 1 in each row in textview txtqty and in each row increment start from 1 and according to quantity I will get total but if in first row i set qty 5 with increment from plus button in next it start from 6 but I want it start from 1 same as first row how I resolve it?

Null Pointer Exception in Android using List

I have following activities to load products from backend. Its a online food ordering with integration of paypal. I tried it in another app its working fine.
I am getting Error on onCreate Method.
There are three activities Item list , Product and product list adapter. I am getting error while loading view. When i commented the lines of adapter its not crashing but after adding the adapters its crashing . Its driving me crazy.
import com.flavorbaba.AppController;
import com.flavorbaba.Config;
import com.flavorbaba.Product;
import com.flavorbaba.ProductListAdapter;
import com.flavorbaba.ProductListAdapter.ProductListAdapterListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
public class ItemsList extends Activity implements ProductListAdapterListener {
private static final String TAG = ItemsList.class.getSimpleName();
private ListView listView;
private Button btnCheckout;
// To store all the products
private List<Product> productsList;
// To store the products those are added to cart
private List<PayPalItem> productsInCart = new ArrayList<PayPalItem>();
private ProductListAdapter adapter;
// Progress dialog
private ProgressDialog pDialog;
private static final int REQUEST_CODE_PAYMENT = 1;
// PayPal configuration
private static PayPalConfiguration paypalConfig = new PayPalConfiguration()
.environment(Config.PAYPAL_ENVIRONMENT).clientId(
Config.PAYPAL_CLIENT_ID);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_menu);
listView = (ListView) findViewById(R.id.list);
btnCheckout = (Button) findViewById(R.id.checkout);
productsList = new ArrayList<Product>();
adapter = new ProductListAdapter(ItemsList.this, productsList, this);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Starting PayPal service
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
startService(intent);
// Checkout button click listener
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check for empty cart
if (productsInCart.size() > 0) {
launchPayPalPayment();
} else {
Toast.makeText(getApplicationContext(),
"Cart is empty! Please add few products to cart.",
Toast.LENGTH_SHORT).show();
}
}
});
// Fetching products from server
fetchProducts();
}
/**
* Fetching the products from our server
* */
private void fetchProducts() {
// Showing progress dialog before making request
pDialog.setMessage("Fetching products...");
showpDialog();
// Making json object request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Config.URL_PRODUCTS, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray products = response
.getJSONArray("products");
// looping through all product nodes and storing
// them in array list
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("p_id");
String name = product.getString("p_name");
String description = product
.getString("p_desc");
String image = product.getString("p_image");
BigDecimal price = new BigDecimal(product
.getString("p_price"));
String sku = product.getString("p_status");
Product p = new Product(id, name, description,
image, price, sku);
productsList.add(p);
}
listView.setAdapter(adapter);
// notifying adapter about data changes, so that the
// list renders with new data
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// hiding the progress dialog
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Verifying the mobile payment on the server to avoid fraudulent payment
* */
private void verifyPaymentOnServer(final String paymentId,
final String payment_client) {
// Showing progress dialog before making request
pDialog.setMessage("Verifying payment...");
showpDialog();
StringRequest verifyReq = new StringRequest(Method.POST,
Config.URL_VERIFY_PAYMENT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "verify payment: " + response.toString());
try {
JSONObject res = new JSONObject(response);
boolean error = res.getBoolean("error");
String message = res.getString("message");
// user error boolean flag to check for errors
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
if (!error) {
// empty the cart
productsInCart.clear();
}
} catch (JSONException e) {
e.printStackTrace();
}
// hiding the progress dialog
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Verify Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hiding the progress dialog
hidepDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("paymentId", paymentId);
params.put("paymentClientJson", payment_client);
return params;
}
};
// Setting timeout to volley request as verification request takes
// sometime
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
verifyReq.setRetryPolicy(policy);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(verifyReq);
}
/**
* Preparing final cart amount that needs to be sent to PayPal for payment
* */
private PayPalPayment prepareFinalCart() {
PayPalItem[] items = new PayPalItem[productsInCart.size()];
items = productsInCart.toArray(items);
// Total amount
BigDecimal subtotal = PayPalItem.getItemTotal(items);
// If you have shipping cost, add it here
BigDecimal shipping = new BigDecimal("0.0");
// If you have tax, add it here
BigDecimal tax = new BigDecimal("0.0");
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(
shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(
amount,
Config.DEFAULT_CURRENCY,
"Description about transaction. This will be displayed to the user.",
Config.PAYMENT_INTENT);
payment.items(items).paymentDetails(paymentDetails);
// Custom field like invoice_number etc.,
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
/**
* Launching PalPay payment activity to complete the payment
* */
private void launchPayPalPayment() {
PayPalPayment thingsToBuy = prepareFinalCart();
Intent intent = new Intent(ItemsList.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingsToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
/**
* Receiving the PalPay payment response
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.e(TAG, confirm.toJSONObject().toString(4));
Log.e(TAG, confirm.getPayment().toJSONObject()
.toString(4));
String paymentId = confirm.toJSONObject()
.getJSONObject("response").getString("id");
String payment_client = confirm.getPayment()
.toJSONObject().toString();
Log.e(TAG, "paymentId: " + paymentId
+ ", payment_json: " + payment_client);
// Now verify the payment on the server side
verifyPaymentOnServer(paymentId, payment_client);
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ",
e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e(TAG, "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.e(TAG,
"An invalid Payment or PayPalConfiguration was submitted.");
}
}
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onAddToCartPressed(Product product) {
PayPalItem item = new PayPalItem(product.getname(), 1,
product.getprice(), Config.DEFAULT_CURRENCY, product.getsku());
productsInCart.add(item);
Toast.makeText(getApplicationContext(),
item.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
--------------------------------------------------------------------------
import java.math.BigDecimal;
public class Product {
private String id, name, description, image, sku;
private BigDecimal price;
public Product() {
}
public Product(String id, String name, String description, String image,
BigDecimal price, String sku) {
this.id = id;
this.name = name;
this.description = description;
this.image = image;
this.price = price;
this.sku = sku;
}
public String getid() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getname() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getdescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getimage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public BigDecimal getprice() {
return price;
}
public String getsku() {
return sku;
}
}
---------------------------------------------------------------
package com.flavorbaba;
import com.flavorbaba.R;
import com.flavorbaba.AppController;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class ProductListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Product> products;
private ProductListAdapterListener listener;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ProductListAdapter(Activity activity, List<Product> feedItems,
ProductListAdapterListener listener) {
this.activity = activity;
this.products = feedItems;
this.listener = listener;
}
#Override
public int getCount() {
return products.size();
}
#Override
public Object getItem(int location) {
return products.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item_product, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.productName);
TextView description = (TextView) convertView
.findViewById(R.id.productDescription);
TextView price = (TextView) convertView.findViewById(R.id.productPrice);
NetworkImageView image = (NetworkImageView) convertView
.findViewById(R.id.productImage);
Button btnAddToCart = (Button) convertView
.findViewById(R.id.btnAddToCart);
final Product product = products.get(position);
name.setText(product.getname());
description.setText(product.getdescription());
price.setText("Price: $" + product.getprice());
// user profile pic
image.setImageUrl(product.getimage(), imageLoader);
btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onAddToCartPressed(product);
}
});
return convertView;
}
public interface ProductListAdapterListener {
public void onAddToCartPressed(Product product);
}
}
This is a lot ta code dude...
I Wonder why your Productlistadapter object needs two contexts and why you give the first context as Item activity.this but nevertheless
One big Problem here is that you are trying to make a network connection on the main thread...that's an error when you are in strict mode while debugging...

how to call Activity asynctask from custom adapter in android

I have made an activity in that i have a listView and ,I have Implemeted a custom adapter for that ListView ,I have implemeted ListItem's textView's Clickevnet,In That I want to call my activity's AsyncTAk inside that customAdapter,CAn anybuddy tell me how can i do that? my code is as below:
main.java
package com.epe.yehki.ui;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.BuyingRequestAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class BuyingreqActivity extends Activity implements OnClickListener {
Button viewReq, postReq;
EditText productName;
TextView productCategory;
TextView expTime;
TextView productDesc;
TextView estOrderQty;
ImageView proImg;
Button send;
ImageView iv_fav_menu;
private int flag = 1;
ScrollView scr_post;
RelativeLayout scr_view;
RelativeLayout quote_view;
private ProgressDialog pDialog;
String viewURL, postURL;
JSONObject jsonObj;
JSONArray requestes = null;
JSONArray quotes = null;
ArrayList<HashMap<String, String>> reqList;
ArrayList<HashMap<String, String>> queList;
private BuyingRequestAdapter buyingRequestContent;
RelativeLayout rl_botm;
ListView lv;
Header header;
Calendar dateandtime;
private static final int PICK_FROM_CAMERA = 100;
private static final int PICK_FROM_GALLERY = 200;
private Uri picUri;
int la, lo;
final int CAMERA_CAPTURE = 1;
private static String fileName;
Intent in = null;
ListView quoteList;
private String imagePath;
private Uri imageUri;
String buyer_request_id, reqID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_buying_request);
InitializeView();
productCategory.setOnClickListener(this);
send.setOnClickListener(this);
expTime.setOnClickListener(this);
proImg.setOnClickListener(this);
dateandtime = Calendar.getInstance(Locale.US);
header.back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
reqList = new ArrayList<HashMap<String, String>>();
queList = new ArrayList<HashMap<String, String>>();
viewReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 2;
reqList.clear();
iv_fav_menu.setBackgroundResource(R.drawable.tab_two_fav);
new GetBuyingReqList().execute();
scr_view.setVisibility(View.VISIBLE);
quote_view.setVisibility(View.GONE);
rl_botm.setVisibility(View.GONE);
scr_post.setVisibility(View.GONE);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
in = new Intent(getApplicationContext(), BuyingRequestDetailActivity.class);
// getting ProductId from the tag...
reqID = reqList.get(position).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::;;THE INTENT FOR THE resuest DETIALS ACTIVITY=================" + reqID);
in.putExtra(Const.TAG_BUYING_REQUEST_ID, reqID);
startActivity(in);
}
});
postReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 1;
iv_fav_menu.setBackgroundResource(R.drawable.tab_one_fav);
quote_view.setVisibility(View.GONE);
scr_post.setVisibility(View.VISIBLE);
rl_botm.setVisibility(View.VISIBLE);
scr_view.setVisibility(View.GONE);
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_pro_cat:
break;
case R.id.tv_pro_exp_tym:
DatePickerDailog dp = new DatePickerDailog(BuyingreqActivity.this, dateandtime, new DatePickerDailog.DatePickerListner() {
#Override
public void OnDoneButton(Dialog datedialog, Calendar c) {
datedialog.dismiss();
dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
dateandtime.set(Calendar.MONTH, c.get(Calendar.MONTH));
dateandtime.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
expTime.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
}
#Override
public void OnCancelButton(Dialog datedialog) {
// TODO Auto-generated method stub
datedialog.dismiss();
}
});
dp.show();
break;
case R.id.btn_send:
new postBuyingReqList().execute();
break;
case R.id.iv_img:
showCustomeAlert2(BuyingreqActivity.this, "Yehki", "From Camera", "From Gallery");
break;
}
}
#SuppressWarnings("deprecation")
private void showCustomeAlert2(Context context, String title, String rightButton, String leftButton) {
final Dialog dialog = new Dialog(BuyingreqActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
dialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialog.setContentView(R.layout.popup_alert);
dialog.setCancelable(false);
final ImageView btn_lft = (ImageView) dialog.findViewById(R.id.iv_left);
final ImageView btn_rgt = (ImageView) dialog.findViewById(R.id.iv_right);
final Button cancel = (Button) dialog.findViewById(R.id.btn_cancle);
final TextView btn_left = (TextView) dialog.findViewById(R.id.btnLeft);
final TextView btn_right = (TextView) dialog.findViewById(R.id.btnRight);
btn_left.setText(leftButton);
btn_right.setText(rightButton);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_rgt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
System.out.println("=========== perform click ==============");
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
System.out.println(" PATH ::: " + imageUri);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
}
dialog.dismiss();
}
});
btn_lft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
dialog.show();
}
void InitializeView() {
iv_fav_menu = (ImageView) findViewById(R.id.iv_fav_menu);
viewReq = (Button) findViewById(R.id.btn_view);
postReq = (Button) findViewById(R.id.btn_post);
scr_post = (ScrollView) findViewById(R.id.scr_post);
scr_view = (RelativeLayout) findViewById(R.id.scr_view);
quote_view = (RelativeLayout) findViewById(R.id.quote_view);
lv = (ListView) findViewById(R.id.req_list);
rl_botm = (RelativeLayout) findViewById(R.id.rl_botm);
header = (Header) findViewById(R.id.headerBuying);
header.title.setText("Post Buying Request");
proImg = (ImageView) findViewById(R.id.iv_img);
quoteList = (ListView) findViewById(R.id.quote_list);
productName = (EditText) findViewById(R.id.et_pro_name);
productCategory = (TextView) findViewById(R.id.tv_pro_cat);
expTime = (TextView) findViewById(R.id.tv_pro_exp_tym);
productDesc = (EditText) findViewById(R.id.et_pro_desc);
estOrderQty = (TextView) findViewById(R.id.et_est_qty);
send = (Button) findViewById(R.id.btn_send);
}
/*
* getting buying request list...!!!
*/
private class GetBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "");
query = query.replace(" ", "%20");
viewURL = Const.API_BUYING_REQUEST_LIST + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String subject = c.getString(Const.TAG_PRODUCT_NAME);
String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);
HashMap<String, String> request = new HashMap<String, String>();
request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
request.put(Const.TAG_PRODUCT_NAME, subject);
request.put(Const.TAG_DATE_MODIFIED, date_modified);
request.put(Const.TAG_EXPIRY_DATE, expired_date);
request.put(Const.TAG_QUOTE_COUNT, quote_count);
request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
reqList.add(request);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
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
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* getting qoute List...!!!
*/
public class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + reqID;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
reqList.add(quote);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
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
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* post Buying Request api()...!!!
*/
private class postBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postURL = Const.API_BUYING_REQUEST + "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_name=" + productName.getText().toString().trim()
+ "&category_id=1&expire_time=" + expTime.getText().toString() + "&detail_desc=" + productDesc.getText().toString().trim() + "&esti_ordr_qty="
+ estOrderQty.getText().toString().trim() + "&esti_ordr_qty_unit=1&filename=abc.jpg&image=abc.png";
// Creating service handler class instance
postURL = postURL.replace(" ", "%20");
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::post buying request URL:::::::::::::::::" + postURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(postURL, BackendAPIService.POST);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.get("status").equals("success")) {
flag = 0;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent i;
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if (flag == 0) {
Utils.showCustomeAlertValidation(BuyingreqActivity.this, "Request Posted", "Yehki", "OK");
clearViews();
} else {
Toast.makeText(BuyingreqActivity.this, "Buying Request has not been posted", 0).show();
}
/**
* Updating parsed JSON data into ListView
*
* */
}
}
void clearViews() {
productName.setText("");
productDesc.setText("");
estOrderQty.setText("");
expTime.setText("Expiration Time");
proImg.setImageResource(R.drawable.noimage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE) { // for camera
try {
System.out.println("============= FILENAME :: " + fileName);
if (new File(Const.DIR_USER + "/" + fileName).exists()) {
performCrop();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) { // for crop image
try {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
Utils.createDirectoryAndSaveFile(thePic, Const.DIR_USER + "/" + fileName);
// pro_pic.setImageBitmap(thePic);
#SuppressWarnings("deprecation")
Drawable dra = (Drawable) new BitmapDrawable(thePic);
proImg.setImageDrawable(dra);
proImg.setScaleType(ScaleType.FIT_XY);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
if (data != null) {
/*
* fileName = Const.DIR_USER + "/" + "user_" +
* Pref.getValue(ProfileActivity.this, Const.PREF_USER_ID, 0) +
* "_" + System.currentTimeMillis() + ".png";
*/
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
Bundle extras2 = data.getExtras();
Bitmap photo = extras2.getParcelable("data");
Utils.createDirectoryAndSaveFile(photo, Const.DIR_USER + "/" + fileName);
ImageView picView = (ImageView) findViewById(R.id.iv_img);
picView.setImageBitmap(photo);
}
}
}
private void performCrop() {
try {
System.out.println("============= AFTER FILENAME :: " + fileName);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 200);// 256
cropIntent.putExtra("outputY", 200);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 2);
}
catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* HERE I WANT TO CALL "GETqUOTElIST" ASYNCTASK OF MY ACTIVITY/////!!!!!!!
*/
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
This might not be the correct approach of coding ,where in you have all the asyncs in one activity.
But to achieve what you want you can use the context that you pass in the adapter like this:
((YourActivityYouArePassing)mContext).someMethod();
the activity's context must be the same as the one you are using for type casting, and someMethod() should be a method declared inside the activity with public keyword.
in someMethod() you could then call your async task like:
public void someMethod() {
new AsyncClass().execute();
}
EDIT:
The onClick will look like this in the adapter
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* HERE I WANT TO CALL "GETqUOTElIST" ASYNCTASK OF MY ACTIVITY/////!!!!!!!
*/
((YourActivityYouArePassing)mContext).someMethod();
}
});
Hope that helps!!
You can call async task on text click inside Custom adapter
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new GetBuyingReqList.execute();
}
});
and make GetBuyingReqList class private to public
put below code where u want
GetBuyingReqList getBuyingReqList = new GetBuyingReqList ();
getBuyingReqList .execute();
Possible duplicate How to Call AsyncTask from Adapter class?
found these answers
move your adapter class inside your activity class and make adapter class as inner class.so you have access for calling Asynctask in adapter
Remove AsyncTask Inner class from activity class and Make AsyncTask as a separate class (put it in your package). After that you can call like this "new Asynctask().execute();" from any where
what i did... i sent an instance of the activity to the adapter while initializing, then i called a method at the activity by activity.method() and this method calls the AsyncTask

unable to set adapter in android getting error in settext

I have made a custom adapter for seting to a listView in android,I am paring some jsondata and want to set in into a list view,I have tried as belo but its not workig,My code as below,pls help me .
myactivity.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.CategoryAdapter;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.ServiceHandler;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class ProSubCategoryActivity extends Activity {
int flag;
public Header header;
public TextView title;
Bitmap bitmap;;
private ProductAdapter productContent;
private CategoryAdapter categoryContent;
// PRODUCTS....
// arrayLists......
public static ArrayList<String> productArray;
public static ArrayList<String> categoryArray;
//
// contacts JSONArray
JSONArray subcategories = null;
JSONArray products = null;
public String catid;
public String id;
String name;
ListView lv;
JSONObject jsonObj;
// Hashmap for ListView
ArrayList<HashMap<String, String>> subcategoryList;
ArrayList<HashMap<String, String>> productList;
private ProgressDialog pDialog;
Intent in = null;
// new
public String proname;
public String prodesc;
public String proimg;
public String proMinOrderQty;
public String proMinPrice;
public String proMaxPrice;
public String proTerms;
public String proId;
// new
// URL to get contacts JSON
private static String url = "http://yehki.epagestore.in/app_api/categories.php";
private static String mainurl = "http://yehki.epagestore.in/";
public String suburl = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
this.header = (Header) findViewById(R.id.headersubcat);
title = (TextView) findViewById(R.id.title);
// getting intent data
categoryArray = new ArrayList<String>();
productArray = new ArrayList<String>();
in = getIntent();
lv = (ListView) findViewById(R.id.list);
categoryContent = new CategoryAdapter(this, categoryArray);
// Get JSON values from previous intent
try {
catid = in.getStringExtra(Const.TAG_CAT_ID);
name = in.getStringExtra(Const.TAG_CAT_NAME);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("::::::::::::::MY CATEGORY ID::::::::::::::IN SUB "
+ catid);
subcategoryList = new ArrayList<HashMap<String, String>>();
productList = new ArrayList<HashMap<String, String>>();
suburl = "http://yehki.epagestore.in/app_api/categories.php?"
+ Const.TAG_CAT_ID + "=" + catid;
System.out.println("::::::::::::::::MY SUBCATEGORY URL::::::::::::"
+ suburl);
title.setText(name);
// Displaying all values on the screen
new GetSubCategories().execute();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
if (flag == 0) {
String catname = ((TextView) view.findViewById(R.id.name))
.getText().toString();
in = new Intent(getApplicationContext(),
SubCategoryTwoActivity.class);
in.putExtra(Const.TAG_CAT_NAME, catname);
in.putExtra(Const.TAG_CAT_ID, catid);
startActivity(in);
} else {
in = new Intent(getApplicationContext(),
ProductDetailActivity.class);
proname = ((TextView) view.findViewById(R.id.product_label))
.getText().toString();
proId = ((TextView) view.findViewById(R.id.pro_id))
.getText().toString();
System.out
.println(":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY================="
+ proname
+ " proDuct Id::::::::::::>>>>>>>>>"
+ proId);
in.putExtra(Const.TAG_PRODUCT_ID, proId);
in.putExtra(Const.TAG_PRODUCT_NAME, proname);
in.putExtra(Const.TAG_PRODUCT_IMG, proimg);
in.putExtra(Const.TAG_PRODUCT_MIN_ORDER_QTY, proMinOrderQty);
in.putExtra(Const.TAG_PRODUCT_MIN_PRICE, proMinPrice);
in.putExtra(Const.TAG_PRODUCT_MAX_PRICE, proMaxPrice);
in.putExtra(Const.TAG_PRODUCT_DESCRIPTION, prodesc);
in.putExtra(Const.TAG_PRODUCT_PAYMENT_TERMS, proTerms);
/*
* in.putExtra(TAG_CAT_NAME, p); in.putExtra(TAG_CAT_ID,
* catid);
*/
startActivity(in);
}
}
});
}
private class GetSubCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ProSubCategoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::"
+ suburl);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(suburl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_CAT_LlIS)) {
System.out
.println("::::::::::::::::true::::::::::::::::"
+ jsonObj.has(Const.TAG_CAT_LlIS));
subcategories = jsonObj
.getJSONArray(Const.TAG_CAT_LlIS);
if (subcategories != null
&& subcategories.length() != 0) {
// looping through All Contacts
flag = 0;
System.out
.println(":::::::::::FLAG IN SUB:::::::::::"
+ subcategories.length());
for (int i = 0; i < subcategories.length(); i++) {
JSONObject c = subcategories.getJSONObject(i);
id = c.getString(Const.TAG_CAT_ID);
String name = c.getString(Const.TAG_CAT_NAME);
// tmp hashmap for single category
/*
* HashMap<String, String> subcategory = new
* HashMap<String, String>();
*
* // adding each child node to HashMap key =>
* // value subcategory.put(Const.TAG_CAT_ID,
* id); subcategory.put(Const.TAG_CAT_NAME,
* name);
*
* // adding contact to contact list
* subcategoryList.add(subcategory);
*/
// new adde 3=04=2014
// categoryArray.add(id);
categoryArray.add(name);
System.out
.println("::::::::::My category:::::::"
+ categoryArray.get(i)
.toString().trim());
}
}
} else if (jsonObj.has(Const.TAG_PRODUCT_LlST)) {
flag = 1;
System.out
.println("::::::::::::::::true::::::::::::::::"
+ jsonObj.has(Const.TAG_PRODUCT_LlST));
products = jsonObj.getJSONArray(Const.TAG_PRODUCT_LlST);
if (products != null && products.length() != 0) {
// looping through All Contacts
System.out
.println(":::::::::::FLAG IN SUB:::::::::::"
+ flag);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
id = c.getString(Const.TAG_PRODUCT_ID);
String proname = c
.getString(Const.TAG_PRODUCT_NAME);
String prodesc = c
.getString(Const.TAG_PRODUCT_DESCRIPTION);
String proimg = Const.API_HOST + "/"
+ c.getString(Const.TAG_PRODUCT_IMG);
System.out
.println(":::::::::::::::My Image Url:::::::::::::"
+ proimg);
String proMinOrderQty = c
.getString(Const.TAG_PRODUCT_MIN_ORDER_QTY);
String proMinPrice = c
.getString(Const.TAG_PRODUCT_MIN_PRICE);
String proMaxPrice = c
.getString(Const.TAG_PRODUCT_MAX_PRICE);
String proTerms = c
.getString(Const.TAG_PRODUCT_PAYMENT_TERMS);
System.out
.println(":::::::::::::My prododuct name+++++++:::::::::::::"
+ proname);
System.out
.println(":::::::::::::My prododuct image+++++++:::::::::::::"
+ proimg);
System.out
.println(":::::::::::::My prododuct min order qty+++++++:::::::::::::"
+ proMinOrderQty);
// tmp hashmap for single category
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
product.put(Const.TAG_PRODUCT_ID, id);
product.put(Const.TAG_PRODUCT_NAME, proname);
product.put(Const.TAG_PRODUCT_IMG, proimg);
product.put(Const.TAG_PRODUCT_MIN_ORDER_QTY,
proMinOrderQty);
product.put(Const.TAG_PRODUCT_DESCRIPTION,
prodesc);
// adding contact to contact list
productList.add(product);
}
}
}
} else {
Log.e("ServiceHandler",
"Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out
.println("::::::::::::::::::got an error::::::::::::");
}
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
*
* */
if (flag == 0) {
lv.setAdapter(categoryContent);
} else {
Toast.makeText(ProSubCategoryActivity.this, "Please wait", 1)
.show();
/*
* ListAdapter adapter = new SimpleAdapter(
* ProSubCategoryActivity.this, productList,
* R.layout.activity_single_produt, new String[] {
* Const.TAG_PRODUCT_ID, Const.TAG_PRODUCT_NAME,
* Const.TAG_PRODUCT_IMG, Const.TAG_PRODUCT_MIN_ORDER_QTY,
* Const.TAG_PRODUCT_DESCRIPTION }, new int[] {
* R.id.product_label, R.id.iv_product_img, R.id.min_qty,
* R.id.pro_desc, R.id.pro_id }); setListAdapter(adapter);
*/
}
}
}
}
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.yehki.R;
public class CategoryAdapter extends BaseAdapter {
private ArrayList<String> categoryArray;
private Context mContext;
public CategoryAdapter(Context paramContext,
ArrayList<String> paramArrayList) {
this.mContext = paramContext;
this.categoryArray = paramArrayList;
}
public int getCount() {
return this.categoryArray.size();
}
public void setAllItems(ArrayList<String> paramArrayList) {
this.categoryArray.addAll(paramArrayList);
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item,
paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.categoryName = ((TextView) paramView
.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.categoryName.setText(categoryArray.get(paramInt)
.indexOf(0));
return paramView;
}
static class Viewholder {
private TextView categoryName;
}
}
I changed your code , try this now
public class CategoryAdapter extends BaseAdapter {
private ArrayList<String> categoryArray;
private Context mContext;
private Viewholder localViewholder = null;
public CategoryAdapter(Context paramContext,
ArrayList<String> paramArrayList) {
this.mContext = paramContext;
this.categoryArray = paramArrayList;
}
public int getCount() {
return this.categoryArray.size();
}
public void setAllItems(ArrayList<String> paramArrayList) {
this.categoryArray.addAll(paramArrayList);
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
if (paramView == null) {
localViewholder = new Viewholder();
paramView = localLayoutInflater.inflate(R.layout.list_item,
paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.categoryName = ((TextView) paramView
.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.categoryName.setText(categoryArray.get(paramInt)
.indexOf(0));
return paramView;
}
static class Viewholder {
private TextView categoryName;
}
}

Categories

Resources