I want to put AsyncTask instead thread in this simple code of SAX RSS parser
in ListFragment , and what is better Asynctask or multi thread.
this is my code
public class ListItem extends ListFragment {
public ArrayList<NewsItem> getValues() {
return values;
}
public void setValues(ArrayList<NewsItem> values) {
this.values = values;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_news_layout, container, false);
return view;
}
enter code here
public void onStart() {
super.onStart();
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
refresh();
listAdapter = new ListAdapter(getActivity(), R.layout.listitem,
getValues());
setListAdapter(listAdapter);
}
enter code here
public void refresh() {
Thread th = new Thread(new Runnable() {
public void run() {
ListHandler listHandler = new ListHandler();
try {
listHandler.processFeed();
setValues(listHandler.getNewsItemList());
listAdapter.setNewsItemList(getValues());
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
Actually Asynctask is also using thread but it is better for onpostexecute and onprexecute()
method callback if you use thread you dont get this by default .
Like this
private class HttpAsyncDealsTask extends
AsyncTask<String, Void, ArrayList<HashMap<String, String>>> {
protected ArrayList<HashMap<String, String>> doInBackground(
String... dealslist) {
ArrayList<HashMap<String, String>> chekinRsp = new ArrayList<HashMap<String, String>>();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// mem_id
String mem_id = user.get(SessionManager.KEY_ID);
String rest_id = getArguments().getString("getid");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("rest_id", rest_id));
nameValuePairs.add(new BasicNameValuePair("mem_id", mem_id));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL, ServiceHandler.POST,
nameValuePairs);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jresponse = new JSONObject(jsonStr);
JSONObject msg = jresponse.getJSONObject(KEY_MSG);
//String error = jresponse.getString(KEY_ERROR);
String msgss = msg.getString(KEY_MSGSS);
String error = msg.getString(KEY_ERROR);
if(error.equalsIgnoreCase("0"))
{
String getid = getArguments().getString("getid");
String getname = getArguments().getString("getname");
String getpoints = getArguments().getString("getpoints");
String getcomp = getArguments().getString("getcomp");
String getmemberpoint = getArguments().getString("getmemberpoint");
System.out.println(getid + getname + getpoints + getcomp + getmemberpoint);
CheckinPref checkin = new CheckinPref(getActivity());
checkin.Prefernce_save(getid
,getname, getpoints
,getcomp, getmemberpoint);
}
map.put(KEY_MSGSS, msgss);
chekinRsp.add(map);
// Log.d("OUT", msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.d("Response", e.getLocalizedMessage());
}
return chekinRsp; // return result
}
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> chekinRsp) {
System.out.println(chekinRsp.get(0).get(KEY_MSGSS));
TextView chekinResp = (TextView) getActivity().findViewById(
R.id.chekinResp);
chekinResp.setText(chekinRsp.get(0).get(KEY_MSGSS));
Button backButton = (Button) getActivity().findViewById(
R.id.btn_restback);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
fm.popBackStack();
}
});
}
}
and start this using
new HttpAsyncDealsTask().execute();
Related
im trying to parse data from SQL Database into Listview.
My PHP script is working because if i run it in the browser i get the content.
If im trying to get the data from my SQL Databse into the listview my app shows nothing.
Here is my MainActivity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "Mylink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity:
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
i solved it using this code in my MAinActivity:
public class Locations extends AppCompatActivity {
private String TAG = Locations.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/loli.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray contacts = new JSONArray(jsonStr);
// Getting JSON Array node
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**3
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Locations.this, contactList,
R.layout.model, new String[]{"name", "email",
"mobile"}, new int[]{R.id.namelist,
});
lv.setAdapter(adapter);
}
}
and used in my CustomlistadapterActivity:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Thanks for your input
Override getCount method into adapter class.
In this i want to cancel the asynctask i called aysnc task in listview onclickitem...
so if there is no data in particular row's then it will stop execution and remain on same activity.
I called the class in click and if condition if false as file_path is null then it will remain on same activity will not proceed further in another activity.
but in my case it will move to another activity i tried lot many things on this like oncancelled(), cancel(), etc methods but they are not working i put all in loop as well as switch case to break.
public class EAdFragment extends Fragment {
ListView lvAdSurvey;
JSONObject json = null;
public static final String FIRST_COLUMN = "Upl_ID";
public static final String SECOND_COLUMN = "File_Description";
JSONArray jarray = null;
JSONObject jsonObj = null;
String upload_type;
String upl_id;
File f;
String imgurl;
ProgressDialog pDialog;
String upl_ID, type_of_upload, file_description, amount;
String file_path = null;
String file_type, related_to, country, state, city, Number_of_user,
type_illegal;
GetData task;
ViewHolder holder;
public ListAdapter adapter;
String text;
public List<EAdvertActivityData> listData = new ArrayList<EAdvertActivityData>();
public void onViewCreated(View view, Bundle savedInstanceState) {
lvAdSurvey = (ListView) view.findViewById(R.id.lvAdSurvey);
new GetList().execute();
lvAdSurvey.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// String text =
// lvAdSurvey.getItemAtPosition(position).toString();
holder = (ViewHolder) view.getTag();
text = holder.txtFirstColumn.getText().toString();
Log.d("text:", text);
task = new GetData();
task.execute();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ead, container,
false);
return rootView;
}
private class GetList extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected JSONObject doInBackground(String... args) {
String url = "url";
JSONParser jParser = new JSONParser();
jsonObj = jParser.getJSONFromUrl(url);
try {
jarray = jsonObj.getJSONArray("result");
Log.d("lengtharray:", String.valueOf(jarray.length()));
for (int i = 0; i < jarray.length(); i++) {
EAdvertActivityData data = new EAdvertActivityData();
JSONObject jobject = new JSONObject(jarray.get(i)
.toString());
upload_type = jobject.optString("Upl_ID").toString();
String description = jobject.optString("File_description")
.toString();
/*
* Log.d("upload_type",upload_type);
* Log.d("description",description);
*/data.setUpl_ID(upload_type);
data.setFile_description(description);
listData.add(data);
Log.d("data:", listData.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObject) {
EAdListViewAdapter adapter = new EAdListViewAdapter(getActivity(),
listData);
lvAdSurvey.setAdapter(adapter);
}
}
private class GetData extends AsyncTask<String, String, String> {
int flag=0;
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
SharedPreferences pref = getActivity().getSharedPreferences(
"SoundSettings", Context.MODE_PRIVATE);
String user_id = pref.getString("user_id", LoginActivity.userid);
String url = "url"
+ text;
JSONParser jParser = new JSONParser();
try {
json = jParser.getJSONFromUrl(url);
Log.d("jsonadvert:", json.toString());
String status = json.getString("fetchdata");
if (status.equals("Success")) {
type_of_upload = json.getString("Type_of_Upload");
file_description = json.getString("File_description");
amount = json.getString("Amount");
file_path = json.getString("file_path");
file_type = json.getString("File_type");
related_to = json.getString("Related_to");
country = json.getString("Country");
// state = json.getString("state");
Number_of_user = json.getString("Number_of_usr");
type_illegal = json.getString("Type_llegal");
Log.d("type_illegal:", type_illegal);
Log.d("file_path:", file_path);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String args) {
pDialog.dismiss();
if(file_path==null){
Toast.makeText(getActivity(), "Image does not exists", Toast.LENGTH_LONG).show();
pDialog.cancel();
task.cancel(true);
}else{
imgurl = "http://sharpersofttech.com/sign_up/" + file_path;
Intent in = new Intent(getActivity(), AdvertActivity.class);
in.putExtra("upl_id", text);
in.putExtra("file_description", file_description);
in.putExtra("imgurl", imgurl);
startActivity(in);
((Activity) getActivity()).overridePendingTransition(0, 0);
}
}
}
}
This question is asked many times but I don't get my actual solution because the ArrayList is in HashMap , so
I am not able to add text in the ListView. I had made a chat , where I got the result of all the chat messages, but when I send text message , it came on top , but when I went back and came again , it came in right way . So my problem is that when I add any text it does not come last or in text view.
//Here is my class
public class ChatScreenActivity extends Activity{
static ArrayList messages = new ArrayList<messageArray>();
ListView list;
Button sendmsg;
EditText usertext;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
private static String sendmsgurl = "http://www.get2love.webitexperts.com/sendmessage";
private static String msgdetailurl = "http://www.get2love.webitexperts.com/getChatDetails";
JSONParser jsonParser = new JSONParser();
ChatMessageListAdapter adapter;
ActionBar actionBar;
/*ArrayList<String> al=new ArrayList<String>();
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,al);
*/
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
arraylist=new ArrayList<HashMap<String,String>>();
new messagedetaillist().execute();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatscreenctivity);
Intent intent= getIntent();
String sender_username=intent.getExtras().getString("User_Name");
list = (ListView) findViewById(R.id.listview1);
list.setCacheColorHint(Color.TRANSPARENT);
list.setDivider(null);
usertext=(EditText)findViewById(R.id.et_sent_msg);
sendmsg=(Button)findViewById(R.id.bt_sent_msg);
actionBar=getActionBar();
actionBar.show();
actionBar.setTitle(sender_username);
actionBar.setSubtitle("messages");
sendmsg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new sendmessage().execute();
}
});
}
class sendmessage extends AsyncTask<Void, Void, Void> {
int flag;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(ChatScreenActivity.this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args0) {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
HashMap<String, String> map = new HashMap<String, String>();
UserModel user=(UserModel)getIntent().getSerializableExtra("User");
String User_id=String.valueOf(user.getUser_Id());
String message=usertext.getText().toString();
Intent intent= getIntent();
String sender_id=intent.getExtras().getString("Sender_id");
params.add(new BasicNameValuePair("SenderUserID",User_id));
params.add(new BasicNameValuePair("ChatText",message));
params.add(new BasicNameValuePair("ReceiverID",sender_id));
ServiceHandler sh = new ServiceHandler();
JSONObject json = jsonParser.makeHttpRequest(sendmsgurl,"POST", params);
Log.d("Create Response", json.toString());
try
{
if(json!=null)
{
if(json.has("status"))
{
String status=json.getString("status");
if(status.equals("Success"))
{
flag=1;
map.put("Chat_Text",message);
map.put("Receiver_User_Id", sender_id);
map.put("User_Id", User_id);
arraylist.add(map);
}
}
else
{
flag=0;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
if(flag==1)
{
Toast.makeText(getApplicationContext(), "Succesfully send", Toast.LENGTH_SHORT).show();
ChatMessageListAdapter adapter = new ChatMessageListAdapter(ChatScreenActivity.this, arraylist);
list.setAdapter(adapter);
mProgressDialog.dismiss();
}
else
{
Toast.makeText(getApplicationContext(), "Failed registered ", Toast.LENGTH_SHORT).show();
}
}
}
class messagedetaillist extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(ChatScreenActivity.this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args0)
{
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
UserModel user=(UserModel)getIntent().getSerializableExtra("User");
String User_id=String.valueOf(user.getUser_Id());
Intent intent= getIntent();
String sender_id=intent.getExtras().getString("Sender_id");
params.add(new BasicNameValuePair("SenderUserID",sender_id));
params.add(new BasicNameValuePair("ReceiverID",User_id));
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(msgdetailurl, ServiceHandler.POST, params);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr.length()>0) {
try {
// Locate the array name in JSON
JSONArray contacts = new JSONArray(jsonStr);
for (int i = 0; i < contacts.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = contacts.getJSONObject(i);
String messages=c.getString("Chat_Text");
String SenderId=c.getString("Receiver_User_Id");
map.put("Chat_Text",messages);
map.put("Receiver_User_Id", SenderId);
map.put("User_Id", User_id);
// map.put("TempUser_Image", USer_Image);
// Set the JSON Objects into the array
arraylist.add(map);
}
}
catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
adapter = new ChatMessageListAdapter(ChatScreenActivity.this, arraylist);
list.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
Here is my Adapter class
public class ChatMessageListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
ChatMessageListAdapter adapter;
public ChatMessageListAdapter(Activity a, ArrayList<HashMap<String, String>> arraylist) {
activity = a;
data = arraylist;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
// items for main crowd list
public TextView txt_message;
public RelativeLayout layout_align;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.message_chat_row, null);
holder.txt_message = (TextView) view.findViewById(R.id.txt_message);
holder.layout_align = (RelativeLayout) view.findViewById(R.id.layout_align);
view.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
resultp=data.get(position);
String type = resultp.get("Receiver_User_Id");
String message =resultp.get("Chat_Text");
String User_id=resultp.get("User_Id");// data.get(position).message;
if (!type.equalsIgnoreCase(User_id)) {
holder.layout_align.setGravity(Gravity.RIGHT);
holder.txt_message.setText(message);
holder.txt_message.setBackgroundResource(R.drawable.bubble_green);
}
else {
holder.layout_align.setGravity(Gravity.LEFT);
holder.txt_message.setText(message);
holder.txt_message.setBackgroundResource(R.drawable.bubble_yellow);
}
} catch (Exception e) {
// TODO: handle exception
}
return view;
}
}
Try this within getView
SearchViewHolder orderViewHolder = null;
if (convertView == null) {
orderViewHolder = new SearchViewHolder();
convertView = inflater.inflate(R.layout.order_list_row, null);
orderViewHolder.setproe((TextView) convertView
.findViewById(R.id.tet1));
orderViewHolder.setbaumber((TextView) convertView
.findViewById(R.id.tet2));
convertView.setTag(orderViewHolder);
//orderViewHolder.getproductname().setTextSize(12);
} else {
orderViewHolder = (SearchViewHolder)convertView.getTag();
}
orderViewHolder.getproductname().setText(""+partProductQTY.ownerPartyId);
orderViewHolder.getbatchnumber().setText(""+partProductQTY.availableToPromiseTotal);
return convertView;
Here partProductQTY is my plain POJO class , inpite of this you need use ArrayList
My data comes dynamically in an array of textviews and I am entering some data in edit texts beside that.
All the data comes in the listview.
what I need to do is I need to transfer all the data in the text views as well as edittexts to another screen on a button click.
How will I achieve that?
Here is my code:
public class S1 extends ListActivity implements OnClickListener {
private ProgressDialog pDialog;
ListView lv;
Button b;
String arry1[], category_main;
int i,key = 0;
private static String url = "http://ashapurasoftech.com/train/test.json";
private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
JSONArray items = null;
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.table1);
lv =getListView();
category_main = "";
new Getitems().execute(category_main);
b =(Button) findViewById(R.id.start);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_Name, name);
startActivity(in);
}
});
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.start: try {
onbuttonclick();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
private void onbuttonclick() throws JSONException {
Set<String> arry = new HashSet<String>();
for(int k=0;k<items.length();k++)
{
JSONObject c = items.getJSONObject(k);
String category = c.getString(TAG_Cat);
arry.add(category);
}
arry1 = arry.toArray(new String[arry.size()]);
TableRow[] tr = new TableRow[arry1.length];
TextView[] tx = new TextView[arry1.length];
TableLayout tl = (TableLayout) findViewById(R.id.tablelayout1);
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S1.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setText(cat);
tr[i] = new TableRow(S1.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
category_main = cat;
if (key==0)
{
key=1;
lv.setVisibility(View.VISIBLE);
}
else if(key==1)
{
key=0;
lv.setVisibility(View.GONE);
}
new Getitems().execute(category_main);
}
});
}
b.setVisibility(View.GONE);
}
private class Getitems extends AsyncTask<Void, Void, Void> {
String cat12 = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(S1.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
public void execute(String categorymain) {
cat12 = categorymain;
execute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray(TAG_a);
for (i = 0; i < items.length(); i++) {
final JSONObject c = items.getJSONObject(i); String cate12 = c.getString(TAG_Cat);
String name = c.getString(TAG_Name);
final HashMap<String, String> item = new HashMap<String, String>();
if(cat12.equalsIgnoreCase(cate12))
{
item.put(TAG_Name,name);
itemList.add(item);
}
}
}
catch (JSONException e) {
e.printStackTrace();
} finally {
}}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
S1.this, itemList,
R.layout.textview, new String[] {TAG_Name},new int[] { R.id.name});
setListAdapter(adapter);
}
}
}
I'm doing an app that has mutiple tab and for each tab has its own activity. after putting the code to load the list on one activity; still listview is not visible at all.
here is my code, somebody please help:
public class BillsActivity extends ListActivity {
private ProgressDialog pDialog;
String mUrl = BayadCenterConstants.BAYAD_URL_BILLERS;
JSONParsers jsonParser = new JSONParsers();
ArrayList<HashMap<String, String>> billerList;
JSONArray billers = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_child_bills);
/*
* Check network connection here
*/
billerList = new ArrayList<HashMap<String, String>>();
new LoadBillers().execute();
}
class LoadBillers extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(BillsActivity.this);
pDialog.setMessage("Downlaoding list ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String json = jsonParser.getBillers(mUrl, params);
Log.d("Billers JSON: ", "> " + json);
try {
billers = new JSONArray(json);
if (billers != null) {
for (int i = 0; i < billers.length(); i++) {
JSONObject c = billers.getJSONObject(i);
String id = c.getString("bid");
String name = c.getString("name");
String status = c.getString("status");
String date_added = c.getString("date_added");
HashMap<String, String> map = new HashMap<String, String>();
map.put("bid", id);
map.put("name", name);
map.put("status", status);
map.put("date_added", date_added);
billerList.add(map);
}
}else{
Log.d("Billers: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
BillsActivity.this, billerList,
R.layout.tab_child_bills_list_row, new String[] { "bid", "name", "status",
"date_added" }, new int[] { R.id.txtBillerID, R.id.txtBillerName,
R.id.txtBillerStatus, R.id.txtBillerDateAdded });
setListAdapter(adapter);
}
});
}
}
this activity is just part of an activity that holds then in tab+swipe manner.
did i miss something with my code?