我在自定义列表适配器中有一个活动类和customlistadapter
我有一个帖子runouithread
,当我用((Activity) context).runOnUiThread(new Runnable()
包裹时,它会给我一个错误消息
它在运行时抛出错误消息ClassCastException: android.app.Application cannot be cast to android.app.Activity
所以请有人帮助我。
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
}
}
答案 0 :(得分:0)
因为在调用此构造函数时:
CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models)
您正在提供getApplicationContext()
。尝试提供context
的{{1}}。
编辑1:
发表评论后:
activity
答案 1 :(得分:0)
从
修改适配器类的构造函数public CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models)
到
public CustomListAdapterfriend(Activity context, List<HashMap<String, Object>> models)
因此,无论何时调用构造函数,IDE都会通知您提供一个Activity作为参数,因此适配器中的强制转换不会失败。