sent parameter to adapter in same class android - java

I have public class StudioDetail (main class) and in StudioDetail I generate private class SendfeedbackKelas like this :
private class SendfeedbackKelas extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariKelas";
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
final String idstudio= extras.getString("STUDIO_ID");
#Override
protected String doInBackground(String... params) {
String date = params[0];
Utils.log("params 1:" + date);
// do above Server call here
kelasstudioList = new ArrayList<KelasStudioModel>();
String responseString = null;
final String url_kelas_studio = Constant.URI_BASE_STUDIO + idstudio + "/class" + "?date=" + date + "&token=" + token;
Utils.log("url kelas studio:"+ url_kelas_studio);
try
{
runOnUiThread(new Runnable() {
public void run() {
new JSONAsyncTask().execute(url_kelas_studio);
ListView listview = (ListView) findViewById(R.id.listView1);
adapter = new ClassSAdapter(context, R.layout.jadwalstudio_info, kelasstudioList);
listview.setAdapter(adapter);
}
});
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
that called ClassSAdapter like this :
private class ClassSAdapter extends ArrayAdapter<KelasStudioModel> {
final Context context = getContext();
ArrayList<KelasStudioModel> kelasstudioList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ClassSAdapter(Context context, int resource, ArrayList<KelasStudioModel> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
kelasstudioList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View.OnClickListener listener1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pesan_kelas);
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
/*studio_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, StudioDetail.class);
startActivity(intent);
}
});*/
dialog.show();
}
};
View.OnClickListener listener2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pelatih);
/*final String url_studio_image = Constant.URI_FRONTEND + "vendor_trainer/20150821052441-tanda-tanya.jpg";
Utils.log("url_studio_image: " + url_studio_image);
new DownloadImageTask((ImageView) dialog.findViewById(R.id.class_image_pelatih)).execute(url_studio_image);*/
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
};
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.kelas = (TextView) v.findViewById(R.id.kelas);
holder.waktu = (TextView) v.findViewById(R.id.waktu);
holder.pelatih = (TextView) v.findViewById(R.id.pelatih);
// set OnClickListeners
holder.kelas.setOnClickListener(listener1);
holder.pelatih.setOnClickListener(listener2);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
//holder.imageview.setImageResource(R.drawable.promo_1);
holder.kelas.setText(kelasstudioList.get(position).getKelas());
holder.waktu.setText(kelasstudioList.get(position).getWaktu());
holder.pelatih.setText(kelasstudioList.get(position).getPelatih());
// set tags
holder.kelas.setTag(position);
holder.waktu.setTag(position);
holder.pelatih.setTag(position);
return v;
}
private class ViewHolder {
public TextView kelas;
public TextView waktu;
public TextView pelatih;
}
}
I want to sent some parameter like this from class JSONAsyncTask to private class ClassSAdapter on View.OnClickListener listener1 and View.OnClickListener listener2 :
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
How to sent that parameter?
As information here is JSONAsynTask class:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
private static final String TAG_CLASSES = "classes";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi classes: " + responseAsText);
JSONObject jsonObj = new JSONObject(responseAsText);
// Getting JSON Array node
JSONArray classes = jsonObj.getJSONArray(TAG_CLASSES);
for(int i=0;i<classes.length();i++){
//HashMap<String, String> promo = new HashMap<String, String>();
JSONObject object = classes.getJSONObject(i);
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
KelasStudioModel actor = new KelasStudioModel();
String starttime = parseDateToHis((String) object.getString("startdate")).toString();
String endtime = parseDateToHis((String) object.getString("enddate")).toString();
actor.setKelas(Html.fromHtml((String) object.getString("masterclass_name")).toString());
actor.setWaktu(starttime + "-" + endtime);
actor.setPelatih(object.getString("trainer_name"));
kelasstudioList.add(actor);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false){
Toast.makeText(context, "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}else{
}
}
}
listener 1 and listener 2 called different dialog.

Related

API Not Searching Food Database When Clicking The Search Button get error Permission denied

Hey Guys I'm working on a calorie app where the user clicks the search button and it supposed to retrieve information from the USDA Food Composition Databases API. For some reason it doesnt do anything and I noticed I get an error in the Logcat.
Im new to Android and to API. Thanks again in advance..
logcat :
Here is the logcat Error I'm Getting
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener {
EditText FoodET,CalorieET;
ImageButton Savebtn, Cancelbtn;
Button searchbutton;
String foodET,calorieET;
//database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry, container,
false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
foodET = ((EditText)
view.findViewById(R.id.foodEditText)).getText().toString();
calorieET = ((EditText)
view.findViewById(R.id.caloriesEditText)).getText().toString();
}
public void saveDataToDB (){
Food food = new Food();
String FoodName = FoodET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(FoodName);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
FoodET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(foodET,CalorieET );
search.execute();
break;
case R.id.SaveBtn:
foodET = FoodET.getText().toString();
calorieET=CalorieET.getText().toString();
if (FoodET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
private class FoodSearch extends AsyncTask<Void, Void, String> {
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food
+"&max=1&offset=0&sort=r&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
ndbno="+ ndbno +"&type=b&format=JSON&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
}
}
}
You Can call the Async task within the same class and SHow alert dialog in the onPost execute section
public class AddEntry extends Fragment implements View.OnClickListener {
EditText DescriptionET,CalorieET; ImageButton Savebtn, Cancelbtn; Button searchbutton; String description , calorieAmt; //database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { // Inflate the layout for this fragment View myView = inflater.inflate(R.layout.fragment_add_entry, container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
DescriptionET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
//save to database:
}
public void saveDataToDB (){
Food food = new Food();
String name = DescriptionET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(name);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
DescriptionET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(description,CalorieET);
search.execute();
break;
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
if (DescriptionET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private class FoodSearch extends AsyncTask<Void, Void, String>{
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food +"&max=1&offset=0&sort=r&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?ndbno="+ ndbno +"&type=b&format=JSON&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
}
}

How to solve the error like java.lang.Throwable: setStateLocked?

I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);

ClassCastException: android.app.Application cannot be cast to android.app.Activity

I have an activity class along with customlistadapter inside customlist adapter.
I have a thread runouithread which give me error msg when i wrap it with ((Activity) context).runOnUiThread(new Runnable().
it throws the error msg at runtime has ClassCastException: android.app.Application cannot be cast to android.app.Activity.
So please some one help me.
public class CustomListAdapterfriend extends BaseAdapter {
List<HashMap<String, Object>> models;
Context context;
LayoutInflater inflater;
URL urll;
HttpURLConnection connection;
InputStream input;
ViewHolder viewHolder;
//UI for Locations
ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2,emasr,cn;
ArrayList<String> listItems;
ListView lv;
public int count1 = 0;
ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
int position2;
String id,emm;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email,session_ph,session_type,session_loc,connter;
ArrayList<HashMap<String, Object>> usersList,usersList1;
JSONParser jParser = new JSONParser();
int i ;
JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
private String imagePath = IP+"/social/upload/";
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
private static String url_all_properties5 = IP+"/social/get_all_agen_like.php";
private static String url_all_properties1 = IP+"/social/get_lik_coun.php";
private static String url_all_properties6 = IP+"/social/get_all_agen_like3.php";
private static String url_all_properties7 = IP+"/social/get_all_dele_like.php";
private static String url_all_properties8 = IP+"/social/get_all_dele_uplike.php";
boolean isSelected;
int a,a1,b,b1;
//private static final String TAG_SUCCESS1 = "mass";
private static final String TAG_USER = "users";
private static final String TAG_PRO = "properties";
//private static final String TAG_PRO1 = "properties1";
// products JSONArray
JSONArray users = null;
//JSONArray users1 = null;
View view;
// JSON Node names
private static final String TAG_SUCCESS = "success";
SharedPreferences sPref;
// int position;
public CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models) {
this.context = context;
this. models = models;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.counters = new int[30];
//this.session_email = sPref.getString("SESSION_UID","");
}
public class ViewHolder {
public TextView countt,idas5,emasr,cn;
// public String id,emm;
public ImageView like;
public ImageView share;
/*public void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
}*/
}
public void clear(){
if(models!=null)
models.clear();
}
#Override
public int getCount() {
return models.size();
}
public HashMap<String, Object> getItem(int position) {
return models.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public View getView( final int position, final View convertView, ViewGroup parent) {
// view = null;
view = convertView;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
sPref= context.getSharedPreferences("REAL", Context.MODE_PRIVATE);
session_email = sPref.getString("SESSION_UID","");
session_ph = sPref.getString("SESSION_PH","");
session_type = sPref.getString("SESSION_TYPE", "");
session_loc = sPref.getString("SESSION_LOC", "");
// lv=(ListView)view.findViewById(R.id.list);
pos = getItemViewType(position);
// long posn = getItemId(position);
// final int paps= (int)posn ;
if (view == null) {
viewHolder = new ViewHolder();
view = inflater.inflate(R.layout.fragment_home2, parent, false);
//your code
//add below code after (end of) your code
viewHolder.idas5 = (TextView) view.findViewById(R.id.hpid);
viewHolder. emasr= (TextView) view.findViewById(R.id.ema);
viewHolder.like=(ImageView)view.findViewById(R.id.likem);
viewHolder.share=(ImageView)view.findViewById(R.id.sharemsp);
viewHolder.cn = (TextView) view.findViewById(R.id.count);
viewHolder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
HashMap<String, Object> item = models.get(position);
String imagePath = (String)item.get("IMAGE").toString();
try {
urll = new URL(imagePath);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection = (HttpURLConnection) urll.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setDoInput(true);
try {
connection.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input = connection.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap immutableBpm = BitmapFactory.decodeStream(input);
if(immutableBpm !=null)
{
Bitmap mutableBitmap = immutableBpm.copy(Bitmap.Config.ARGB_8888, true);
View view = new View(context);
view.draw(new Canvas(mutableBitmap));
String path = Images.Media.insertImage(context.getContentResolver(), mutableBitmap, "Nur", null);
Uri uri = Uri.parse(path);
/* image = (ImageView) view.findViewById(R.id.feedImage1);
Drawable mDrawable = image.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
String path = Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);*/
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(share, "Share Image!"));
}
else
{
Toast.makeText(context, "No image to share", Toast.LENGTH_LONG).show();
}
}
});
// viewHolder.share.setOnItemClickListener(this);
viewHolder.like.setBackgroundResource(R.drawable.like1);
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
// viewHolder.countt = (TextView) v.findViewById(R.id.count);
HashMap<String, Object> item = models.get(position);
viewHolder.idas5.setText((CharSequence) item.get("UIDAS"));
// id=(String) viewHolder.idas5.getText();
viewHolder.emasr.setText((CharSequence) item.get("EMAILM"));
id=(String) viewHolder.idas5.getText();
emm=(String) viewHolder.emasr.getText();
new LoadAllProducts().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
/*if( viewHolder.like.isSelected()){
viewHolder.like.setSelected(false);
//viewHolder.like.setBackgroundResource(R.drawable.like2);
new LoadAllProducts7().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
}
else if(!viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
// viewHolder.like.setBackgroundResource(R.drawable.like1);
new LoadAllProducts().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
}*/
}
});
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.like.setTag(position);
viewHolder.share.setTag(position);
final HashMap<String, Object> item = getItem(position);
/* name.setText(((String)item.get(R.id.name)));
*
*
*/
new LoadAllProducts78().execute();
// boolean isSelected = (Boolean) item.get("selected");
/*if (viewHolder.like.isSelected()) {
viewHolder.like.setSelected(false);
viewHolder.like.setBackgroundResource(R.drawable.like2);
} else if (!viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
viewHolder.like.setBackgroundResource(R.drawable.like1);
} */
pic = (ImageView) view.findViewById(R.id.profilePic);
name = (TextView) view.findViewById(R.id.name);
idas = (TextView) view.findViewById(R.id.hpid);
idas2 = (TextView) view.findViewById(R.id.hpid2);
timestamp = (TextView) view.findViewById(R.id.timestamp);
msg = (TextView) view.findViewById(R.id.txtStatusMsg);
url = (TextView) view.findViewById(R.id.txtUrl);
image = (ImageView) view.findViewById(R.id.feedImage1);
idas.setText((CharSequence) item.get("UIDAS"));
viewHolder.cn.setText((CharSequence) item.get("COUN"));
// listItems.add(idas.getText().toString());
name.setText((CharSequence) item.get("NAME"));
timestamp.setText((CharSequence) item.get("TIME"));
msg.setText((CharSequence) item.get("MSG"));
url.setText((CharSequence) item.get("URL"));
//countt.setText((CharSequence) item.get("COUN"));
//count.setText("" + count1);
int w = image.getWidth();
int h = image.getHeight();
if (w > 1000)
{
a=w-1000;
b=w-a;
}
else
{
b=w;
}
if (h > 1000)
{
a1=h-1000;
b1=h-a1;
}
else
{
b1=h;
}
Picasso.with(context)
//.load("PIC")
.load((String)item.get("PIC"))
.placeholder(R.drawable.profile_dummy)
//.error(R.drawable.ic_whats_hot)
.resize(50, 50)
// .centerCrop()
// .fit()
.into(pic);
/*Display display = getActivity().getWindowManager().
getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;*/
Picasso.with(context)
.load((String)item.get("IMAGE"))
//.load("IMAGE")
// .placeholder(R.drawable.ic_pages)
//.error(R.drawable.ic_home)
.resize(1000,image.getHeight())
.onlyScaleDown()
//.centerCrop()
// .fit().centerInside()
.into(image);
return view;
}
protected ContentResolver getContentResolver() {
// TODO Auto-generated method stub
return null;
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
/*Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("loc", "liked"));
params.add(new BasicNameValuePair("con", "1"));
params.add(new BasicNameValuePair("idtes", id));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties5, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All start: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
Log.d("Inside success...", json.toString());
connter = json.getString("loca");
Intent intent = ((Activity) context).getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
sPref.edit().putString("SESSION_UID", session_email).commit();
sPref.edit().putString("SESSION_TYPE", session_type).commit();
sPref.edit().putString("SESSION_PH", session_ph).commit();
sPref.edit().putString("SESSION_LOC", session_loc).commit();
((Activity) context).finish();
((Activity) context).overridePendingTransition(0, 0);
((Activity) context).startActivity(intent);
((Activity) context).overridePendingTransition(0, 0);
//Toast.makeText(context, "Already liked", Toast.LENGTH_LONG).show();
}
else if (success== 5){
// no products found
Toast.makeText(context, "Already liked", Toast.LENGTH_LONG).show();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
// pDialog.dismiss();
}
}
class LoadAllProducts78 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*pDialog = new ProgressDialog(Friendsprofile.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
*/
/*Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
//usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties6, "POST", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All bastart: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
viewHolder.like.setBackgroundResource(R.drawable.like1);
viewHolder.like.setSelected(true);
}
else if(success == 2) {
viewHolder.like.setBackgroundResource(R.drawable.like2);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
//pDialog.dismiss();
}
}
class LoadAllProducts22 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_properties1, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All Productgetting start: ", json.toString());
// Checking for SUCCESS TAG
try {
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
}
else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
}
}
class LoadAllProducts7 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("loc", "liked"));
params.add(new BasicNameValuePair("con", "1"));
params.add(new BasicNameValuePair("idtes", id));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties7, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All start: ", json.toString());
// Checking for SUCCESS TAG
try {
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
// new LoadAllProducts22().execute();
// products found
// Getting Array of Products
/*users = json.getJSONArray(TAG_PRO);
//users1 = json.getJSONArray(TAG_PRO1);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
//ImageView imageView = (ImageView) findViewById(R.id.profilePic);
// Storing each json item in variable
//String scpass = countt.getText().toString();
String uid = c.getString("uid1"); //from php blue
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put("UIDAS", uid); //from
map.put("PIC", pic);
usersList.add(map);
//usersList1.add(map);
// creating new HashMap
}*/
}
else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
}
}
Because while calling this constructor:
CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models)
You are providing getApplicationContext(). Try to provide context of the activity.
Edit 1:
Following the comments:
CustomListAdapterfriend adapter = new CustomListAdapterfriend(Friendsprofile.this, usersList); lv.setAdapter(adapter);
Modify the constructor of your adapter class from
public CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models)
to
public CustomListAdapterfriend(Activity context, List<HashMap<String, Object>> models)
So whenever you call the constructor, the IDE will notify you to provide an Activity as a parameter, so the cast in your adapter won't fail.
While using in fragments try requireActivity() instead of getApplicationContext()
CustomListAdapterfriend(requireActivity(), List<HashMap<String, Object>> models)

java.lang.IllegalStateException:The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged

I have a sliding image that extends pageradapter. At first it was working. But when i open new activity then press the back button the app is crashing and i've got this error :
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 10, found: 0 Pager id: malate.denise.chelsie.igphthesisbfinal:id/pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class malate.denise.chelsie.igphthesisbfinal.SlidingImage_Adapter
Here's my SlidingImage_Adapter.class
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Pictures> IMAGES;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context,ArrayList<Pictures> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.slidingimage_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
new DownloadImageTask(imageView).execute(IMAGES.get(position).getPhotopath());
// imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
notifyDataSetChanged();
}
#Override
public Parcelable saveState() {
return null;
}
and my AttractionInfo.class
public class AttractionInfo extends ActionBarActivity implements View.OnClickListener {
TextToSpeech tts;
TextView nameofplace,location,exact_address,operatinghours,info;
String nameofplace_s,location_s,exact_address_s,operatinghours_s,info_s,latlang_s,path_s,category_s;
ImageView play,rate,addtoplan,map;
ArrayList<Pictures> records;
private static ViewPager mPager;
private static int currentPage = 0;
String line=null;
private static int NUM_PAGES = 0;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_info);
map = (ImageView)findViewById(R.id.map);
map.setOnClickListener(this);
records=new ArrayList<Pictures>();
nameofplace = (TextView) findViewById(R.id.nameofplace);
info = (TextView) findViewById(R.id.info);
exact_address = (TextView) findViewById(R.id.exact_address);
location = (TextView)findViewById(R.id.location);
operatinghours=(TextView)findViewById(R.id.operatinghours);
play = (ImageView) findViewById(R.id.play);
rate = (ImageView) findViewById(R.id.rate);
addtoplan = (ImageView)findViewById(R.id.addtoplan);
addtoplan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
play.setOnClickListener(this);
rate.setOnClickListener(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setDisplayShowTitleEnabled(false);
tts = new TextToSpeech(AttractionInfo.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
if (extras != null) {
nameofplace_s = extras.getString("name");
nameofplace.setText(nameofplace_s);
info_s = extras.getString("description");
info.setText(info_s);
exact_address_s = extras.getString("exactaddress");
exact_address.setText(exact_address_s);
location_s = extras.getString("location");
location.setText(location_s);
operatinghours_s=extras.getString("operatinghours");
operatinghours.setText(operatinghours_s);
latlang_s = extras.getString("latlang");
path_s=extras.getString("path");
category_s = extras.getString("category");
}
}
public void onStart() {
super.onStart();
fetchphoto bt = new fetchphoto();
bt.execute();
}
#Override
protected void onPause() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onClick(View v) {
if (v == play) {
String speech1 = nameofplace.getText().toString();
String speech2 = info.getText().toString();
String speech = speech1 + "." + speech2;
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
} else if (v==rate){
Intent myIntent = new Intent(this, ListOfReviews.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if(v==addtoplan){
Intent myIntent = new Intent(this, AddPlan.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if (v == map){
Intent myIntent = new Intent(this, Map.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
myIntent.putExtra("latlang",latlang_s);
myIntent.putExtra("address",exact_address_s);
myIntent.putExtra("path",path_s);
startActivity(myIntent);
}
}
private void init() {
SlidingImage_Adapter adapter = new SlidingImage_Adapter(this,records);
for(int i=0;i<records.size();i++){
Pictures pics = records.get(i);
String pic = pics.getPhotopath();
adapter.notifyDataSetChanged();
}
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
CirclePageIndicator indicator = (CirclePageIndicator)
findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
NUM_PAGES =records.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
},5000, 5000);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
private class fetchphoto extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("cityname", nameofplace_s));
try
{
records.clear();
HttpParams httpParams = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getphoto.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Pictures p = new Pictures();
p.setPhotoname(json_data.getString("photo_name"));
p.setPlacename(json_data.getString("place_name"));
p.setCategory(json_data.getString("category"));
p.setPhotopath(json_data.getString("path"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
init();
}
}
}
I've red some similar problems and learned that adding notifychanged may solved the problem but i dont where to place it. Hope you can help m . thanks

ListView Doesn't display anymore than 8 ImageViews

I am decoding jpeg images from a server request I get using json. I display them with a custom ListView Adapter along with a little text.
The images display correctly for the first 8 ImageViews in the ListView, however, after that it will no longer display the image (it will display the text). For example, if I have a total of 10 images, the last two images will not show in the ListView, but if I delete the first 2 images, the last two will show, so there is no concern about retrieving the actual images.
On my main activity (NotesActivity) I have a button that goes to another activity which does an asyntask, and in that async task in the onPostExecute, it returns back to the main activity where it should show the updated list (and it does, unless there are more than 8 images).
I don't know where to begin, any suggestions?
My Activity that contains the ListView
public class NotesActivity extends Activity implements OnClickListener {
String key = "NOTES";
String key2 = "UPDATE_NOTES";
Gson gson = new Gson();
// Notes myNotes = new Notes();
NotesList myNotes = new NotesList();
String bId;
String res = null;
EditText notes;
Button save;
private Button createNote;
private int position;
private String type;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_layout);
createNote = (Button) findViewById(R.id.notes_layout_btn_createNote);
Bundle bundle = this.getIntent().getExtras();
position = bundle.getInt("position");
type = bundle.getString("type");
//
if (type.equals("LISTINGS")) {
Listings it = ListingsFragment.myListings.getListings().get(
position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
//
if (type.equals("SHARED")) {
Listings it = SharedFragment.myShared.getListings().get(position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
GetNotes getNotes = new GetNotes();
try {
NotesList copy = new NotesList();
getNotes.execute(key, bId).get();
for (int j = 0; j < myNotes.getNotes().size(); j++) {
Notes note = myNotes.getNotes().get(j);
System.out.println("Removed value: " + note.getIsRemoved());
if (note.getIsRemoved() == null) {
copy.getNotes().add(note);
}
}
NotesAdapter adapter = new NotesAdapter(this, R.layout.note_row,
copy.getNotes());
ListView lv = (ListView) findViewById(R.id.notes_layout_lv_notesList);
lv.setAdapter(adapter);
} catch (Exception e) {
}
createNote.setOnClickListener(this);
}
private class GetNotes extends AsyncTask<String, String, NotesList> {
#Override
protected NotesList doInBackground(String... things) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", things[0]));
postParameters.add(new BasicNameValuePair("bId", things[1]));
// String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
res = response.toString();
// System.out.println("This is the response " + res);
// res = res.trim();
// res= res.replaceAll("\\s+","");
// error.setText(res);
// System.out.println(res);
myNotes = gson.fromJson(res, NotesList.class);
// System.out.println(res);
} catch (Exception e) {
res = e.toString();
}
return myNotes;
}
#Override
protected void onPostExecute(NotesList res) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.notes_layout_btn_createNote:
ProfileDataSource datasource = new ProfileDataSource(this);
datasource.open();
PropClipGlobal pcg = datasource.getUserIdenity();
Intent intent = new Intent(this, NewNoteActivity.class);
intent.putExtra("bId", bId);
intent.putExtra("uId", pcg.getUID());
intent.putExtra("username", pcg.getEm());
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
}
}
}
My custom adapter
public class NotesAdapter extends ArrayAdapter<Notes> {
List<Notes> notes;
Context context;
public NotesAdapter(Context context, int resource, List<Notes> notes) {
super(context, resource, notes);
this.notes = notes;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.note_row, null);
}
Notes note = notes.get(position);
ImageView icon = (ImageView) v.findViewById(R.id.note_row_icon);
TextView name = (TextView) v.findViewById(R.id.note_row_name);
TextView message = (TextView) v.findViewById(R.id.note_row_message);
TextView date = (TextView) v.findViewById(R.id.note_row_date);
String input = note.getNoteDate();
SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputDf = new SimpleDateFormat("dd, yyyy");
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
Date myDate = null;
try {
myDate = inputDf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
String month = monthFormat.format(myDate);
date.setText(getMonth(Integer.parseInt(month)) + " "
+ outputDf.format(myDate));
message.setText(note.getNote());
name.setText(note.getFirstName() + " " + note.getLastName());
// System.out.println(p.getFileData());
byte[] imageAsBytes = Base64.decode(note.getFileData().getBytes(),
position);
icon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
System.out.println(note.getFileData());
return v;
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1];
}
}
Activity which eventually goes to the main activity (NotesActivity)
public class NewNoteActivity extends Activity implements OnClickListener {
private String uId;
private String bId;
private String username;
private String response;
private String key = "UPDATE_NOTES";
private Button submit;
private EditText note;
private int position;
private String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
submit = (Button) findViewById(R.id.activity_new_note_btn_submit);
note = (EditText) findViewById(R.id.activity_new_note_et_note);
Intent intent = getIntent();
bId = intent.getStringExtra("bId");
uId = intent.getStringExtra("uId");
username = intent.getStringExtra("username");
position = intent.getIntExtra("position", 0);
type = intent.getStringExtra("type");
submit.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.new_note, menu);
return true;
}
private class UpdateNotes extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... values) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", values[0]));
postParameters.add(new BasicNameValuePair("bId", values[1]));
postParameters.add(new BasicNameValuePair("uId", values[2]));
postParameters.add(new BasicNameValuePair("username", values[3]));
postParameters.add(new BasicNameValuePair("note", values[4]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
response = response.toString();
} catch (Exception e) {
response = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String response) {
Intent intent = new Intent(getApplicationContext(),
NotesActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
Toast toast = Toast.makeText(getApplicationContext(),"Added note!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
#Override
public void onClick(View v) {
String noteMessage = note.getText().toString();
UpdateNotes updateNotes = new UpdateNotes();
updateNotes.execute(key, bId, uId, username, noteMessage);
}
}

Categories

Resources