updating onlistitemclick listview from async just really confused - android

Ok this is my first every android app so don't bash me. I am very open to suggestion if I am doing anything wrong or weird so please don't be shy. I'm have a little bit of trouble updating my listview after I click on an item. Anyways here's the code... I just don't understand how it works I think...
[ MainActivity.java ]
package com.mycompany.myapp2;
import android.app.*;
import android.os.*;
import android.text.method.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import java.util.*;
import java.io.*;
public class MainActivity extends ListActivity
{
public CustomAdapter adapterMain;
private FtpConnectionTask ftpTask;
private LayoutInflater mInflater;
private Vector<RowData> data;
private TextView textView;
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.txtView);
textView.setMovementMethod(new ScrollingMovementMethod());
xBins(textView);
}
/*public void addItems( ListView parent )
{
CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
RowData rd = new RowData("item4", "description4");
data.add(rd);
rd = new RowData("item5", "description5");
data.add(rd);
rd = new RowData("item6", "description6");
data.add(rd);
CustomAdapter adapter = new CustomAdapter(this, R.layout.row, R.id.item, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}*/
public void onListItemClick( ListView parent, View v, int position, long id )
{
ftpTask.row = ftpTask.adapter.getItem(position);
String ftpItem = ftpTask.row.mItem;
if ( ftpTask.row.mDescription == "dir" )
{
String[] args = new String[] { ftpItem };
Object[] aObject = new Object[] { "cd", args, this };
//ftpTask.adapter.clear();
//ftpTask.processCmd(aObject);
}
}
private class RowData
{
protected String mItem;
protected String mDescription;
RowData( String item, String description )
{
mItem = item;
mDescription = description;
}
#Override
public String toString( )
{
return mItem + " " + mDescription;
}
}
private class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter( Context context, int resource,
int textViewResourceId, List<RowData> objects )
{
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView( int position, View convertView, ViewGroup parent )
{
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if ( null == convertView )
{
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
private class ViewHolder
{
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder( View row )
{
mRow = row;
}
public TextView getDescription( )
{
if ( null == description )
{
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem( )
{
if ( null == item )
{
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
public void xBins( View view )
{
IrcConnectionTask task = new IrcConnectionTask();
task.execute(new Object[] { "irc.efnet.pl", 6667, "sgd5", this });
}
}
[ IrcConnectionTask.java ]
package com.mycompany.myapp2;
import android.os.*;
import java.io.*;
import java.net.*;
public class IrcConnectionTask extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private Socket socket;
#Override
protected String doInBackground(Object... params)
{
String response = "";
String host = (String)params[0];
Integer port = (Integer)(params[1]);
String nick = (String)params[2];
callerActivity = (MainActivity)params[3];
try
{
socket = new Socket(host, port);
String msg1 = "NICK " + nick;
String msg2 = "USER sur 8 * :be";
String messages[] = { msg1, msg2 };
InputDumper task = new InputDumper();
task.execute(new Object[] { socket, messages, nick, callerActivity});
}
catch ( UnknownHostException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
#Override
protected void onProgressUpdate(String result)
{
//textView.setText(result);
}
}
[ InputDumper.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import java.io.*;
import java.net.*;
import android.widget.*;
public class InputDumper extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private String response = "";
private Integer i = 0;
private Boolean Connected = false;
protected String doInBackground(Object... params)
{
try
{
Socket socket = (Socket)params[0];
String messages[] = (String[])params[1];
String nickname = (String)params[2];
callerActivity = (MainActivity) params[3];
//Pattern pattern = Pattern.compile("USERNAME: (.*)");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg = bufferedReader.readLine()) != null)
{
if (msg.indexOf("USERNAME:") > 0)
{
new FtpConnectionTask().execute(new Object[] { nickname, "emulation", callerActivity });
publishProgress("FTP CONNECTION STARTED!!!");
}
if (msg.startsWith("PING"))
{
String PONG = "PONG " + msg.substring(msg.indexOf(":"));
new OutputWriter().execute(new Object[] { socket, PONG, callerActivity });
Connected = true;
}
else if (i == 4)
{
for (String message : messages)
{
new OutputWriter().execute(new Object[] { socket, message, callerActivity });
}
}
else if (i == 13) //msg.endsWith("servers"))
{
new OutputWriter().execute(new Object[] { socket, "JOIN #xbins", callerActivity });
}
else if (i == 20)
{
new OutputWriter().execute(new Object[] { socket, "PRIVMSG #xbins :!list", callerActivity });
}
response += msg;
publishProgress(msg);
i++;
}
}
catch (IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
private TextView textView;
#Override
protected void onProgressUpdate(String... progress)
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='green'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
}
[ OutputWriter.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import java.io.*;
import java.net.*;
import android.widget.*;
public class OutputWriter extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private String response = "";
protected String doInBackground(Object... params)
{
try
{
Socket socket = (Socket)params[0];
String message = (String)params[1];
callerActivity = (MainActivity)params[2];
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(message + "\n\r");
bufferedWriter.flush();
publishProgress(message);
}
catch (IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
private TextView textView;
#Override
protected void onProgressUpdate(String... progress)
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='red'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
}
[ FtpConnectionTask.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import android.util.*;
import android.widget.*;
import java.io.*;
import org.apache.commons.io.*;
import org.apache.commons.net.ftp.*;
import java.util.*;
import android.view.*;
import android.content.*;
import android.app.*;
public class FtpConnectionTask extends AsyncTask<Object, String, String>
{
public static CustomAdapter adapter;
public static RowData row;
MainActivity callerActivity;
private LayoutInflater mInflater;
public Vector<RowData> data;
private FTPClient mFTPClient = new FTPClient();
protected String doInBackground( Object... params )
{
try
{
if ( mFTPClient.isConnected() )
{
Log.v("TESTING", "Is connected");
String cmd = (String)params[0];
String[] args = (String[])params[1];
callerActivity = (MainActivity) params[2];
if (cmd == "cd")
{
mFTPClient.changeWorkingDirectory(args[0].toString());
String[] names = mFTPClient.listNames();
listRemote(names);
}
}
else
{
String user = (String)params[0];
String pass = (String)params[1];
callerActivity = (MainActivity) params[2];
mFTPClient.connect("distribution.xbins.org");
mFTPClient.login(user, pass);
mFTPClient.enterLocalActiveMode();
mFTPClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
publishProgress("WORKING DIR: " + mFTPClient.printWorkingDirectory());
publishProgress("LOGGED IN");
String[] names = mFTPClient.listNames();
listRemote(names);
FTPFile[] remoteFiles = mFTPClient.listFiles();
for ( FTPFile remoteFile : remoteFiles ) //int i = 0; i < remoteFiles.length; i++)
{
if ( remoteFile.getType() == FTPFile.FILE_TYPE )
{
String name = remoteFile.getName();
long length = remoteFile.getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
publishProgress(name + ":\t\t" + readableLength);
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
final void listRemote(final String... params)
{
callerActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mInflater = (LayoutInflater) callerActivity.getSystemService(callerActivity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for ( String name : params )
{
row = new RowData(name, "dir");
data.add(row);
}
adapter = new CustomAdapter(callerActivity, R.layout.row, R.id.item, data);
callerActivity.setListAdapter(adapter);
callerActivity.getListView().setTextFilterEnabled(true);
}
});
}
private TextView textView;
#Override
protected void onProgressUpdate( String... progress )
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='yellow'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if ( scrollAmount > 0 )
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
public class RowData
{
protected String mItem;
protected String mDescription;
RowData( String item, String description )
{
mItem = item;
mDescription = description;
}
#Override
public String toString( )
{
return mItem + " " + mDescription;
}
}
public class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter( Context context, int resource,
int textViewResourceId, List<RowData> objects )
{
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView( int position, View convertView, ViewGroup parent )
{
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if ( null == convertView )
{
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
public class ViewHolder
{
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder( View row )
{
mRow = row;
}
public TextView getDescription( )
{
if ( null == description )
{
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem( )
{
if ( null == item )
{
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
}
[ row.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#00000000">
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false" />
</LinearLayout>
[ main.xml ]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
android:id="#+id/txtView"
android:maxLines = "5"
android:scrollbars = "vertical" />
<ListView
android:id="#android:id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_below="#+id/txtView" />
</RelativeLayout>

Related

How to get value from listview checkbox?

I am having a little trouble with listview, I want to get values of listview whose checkbox are selected when button is clicked. till now i have created a listview with checkboxes and fetched all the values from mysql but i am not able to get values of listview which are checked.
This is my class
public class ListViewMultipleSelectionActivity extends Activity{
Button button;
String myJSON;
private static final String TAG_NAME = "cat_name";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
personList = new ArrayList<HashMap<String,String>>();
list1 = (ListView) findViewById(R.id.list);
button = (Button)findViewById(R.id.testbutton);
getlat();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void getlat(){
class GetDataJSON extends AsyncTask<String, Void, String> {
public void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = null;
try {
URL url = new URL("http://xxxxxxxxxxxx/category.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder("");
String line="";
while ((line = in.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
}
assert inputStream != null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
ListViewMultipleSelectionActivity.this, personList, R.layout.result,
new String[]{TAG_NAME},
new int[]{R.id.name}
);
list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list1.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/testbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Submit" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/testbutton"
android:layout_alignParentTop="true"/>
</RelativeLayout>
result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
</CheckBox>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
android:layout_weight="1" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
i have implemented this on testbutton(Button) click please check
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = list1.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
String[] valuess = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
valuess[i] = selectedItems.get(i);
}
Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show();
}
});
this is i am getting after click
E/-->>>>: [Ljava.lang.String;#ca01299
What you can do is creating a custom class to store these values along with a custom adapter that supports it. So whenever you click the button you can call the given function to retrieve the statuses of those items. Example architecture given below:
PS: Since I don't know what you want to do with checked values, I left you there with comments which you can change with your need.
MainActivity.java
package com.rencsaridogan.stackoverflow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ExampleClass> objects;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objects = new ArrayList<>();
for (int i = 0; i < 10; i++){
objects.add(new ExampleClass("Example Name " + i));
}
final ListView listView = (ListView) findViewById(R.id.listView);
final Button testButton = (Button) findViewById(R.id.testButton);
final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects);
listView.setAdapter(exampleAdapter);
exampleAdapter.notifyDataSetChanged();
testButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
getCheckedItems();
}
});
}
private void getCheckedItems(){
for (int i = 0; i < 10; i++) {
if (objects.get(i).isChecked()){
Log.i("MainActivity",i + " is checked");
/**
* Value is checked, do what you need to do here
*/
} else {
Log.i("MainActivity",i + " is NOT checked");
/**
* Value is NOT checked
*/
}
}
}
}
ExampleAdapter.java
package com.rencsaridogan.stackoverflow;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleAdapter extends ArrayAdapter<ExampleClass> {
ArrayList<ExampleClass> objects;
Listener listener;
Context context;
public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) {
super(context, resource);
this.context = context;
this.objects = objects;
}
#Override public int getViewTypeCount() {
return super.getViewTypeCount();
}
#Override public int getCount() {
return objects.size();
}
#SuppressLint("InflateParams") #Override public View getView(int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
Log.i("ExampleAdapter","ConvertView inflated");
convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false);
}
Log.i("ExampleAdapter","Setting of values");
final ExampleClass data = objects.get(position);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
viewHolder.textView.setText(data.getName());
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.setChecked(isChecked);
}
});
return convertView;
}
public void setListener(Listener listener) {
this.listener = listener;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
public ArrayList<ExampleClass> getObjects() {
return objects;
}
public void setObjects(ArrayList<ExampleClass> objects) {
this.objects = objects;
notifyDataSetChanged();
}
#Override public long getItemId(int position) {
return super.getItemId(position);
}
public interface Listener {
void onCheckedChanged(int position);
}
}
ExampleClass.java
package com.rencsaridogan.stackoverflow;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleClass {
String name;
boolean isChecked;
public ExampleClass(String name) {
this.name = name;
}
public ExampleClass(String name, boolean isChecked) {
this.name = name;
this.isChecked = isChecked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
}
Set checkbox object as tag to your row view that might be your 'convertView' in getView() method of your adapter.
Write on click listener on your row view.
3.Inside that click-listener to row view getTag from view that's parameter in onClick method and cast it to checkbox and then setChecked to true for that checkbox object.
code might look like this,
convertView.setTag(yourCheckBoxObject);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v.getTag();
cb.setChecked(true);
}
});
Please refer this sight for more information Getting an issue while checking the dynamically generated checkbox through list view
In your Adapter there was one #override method called getView() in that method you will get the current item which you will clicked
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox checkBox=(CheckBox) view;
String tagName="";
if(checkBox.isChecked()){
tagName=checkBox.getTag().toString();
deleteServices.add(tagName);
checkboxArrayList.add(checkBox);
}else {
checkboxArrayList.remove(checkBox);
tagName=checkBox.getTag().toString();
if(deleteServices.size()>0&&deleteServices.contains(tagName)){
deleteServices.remove(tagName);
}
});

Android - How to handle ratingBar in custom adapter?

I have a TextView and RatingBar in ListView, and i want to save value of RatingBar on each list in ListView, it is possible with custom adapter??
the code I use to do likes:
PertanyaanAdapter.java
package flix.yudi.pertanyaan3;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.List;
class PertanyaanAdapter extends ArrayAdapter<Pertanyaan> {
private AppCompatActivity activity;
private List<Pertanyaan> movieList;
PertanyaanAdapter(AppCompatActivity context, int resource, List<Pertanyaan> objects) {
super(context, resource, objects);
this.activity = context;
this.movieList = objects;
}
#Override
public Pertanyaan getItem(int position) {
return movieList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
//holder.ratingBar.getTag(position);
}
holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));
holder.ratingBar.setTag(position);
holder.ratingBar.setRating(getItem(position).getRatingStar());
holder.movieName.setText(getItem(position).getAsk());
return convertView;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
Pertanyaan item = getItem(position);
assert item != null;
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}
private static class ViewHolder {
private RatingBar ratingBar;
private TextView movieName;
ViewHolder(View view) {
ratingBar = (RatingBar) view.findViewById(R.id.rate_img);
movieName = (TextView) view.findViewById(R.id.text);
}
}
}
Pertanyaan.java
package flix.yudi.pertanyaan3;
public class Pertanyaan {
private float ratingStar;
private String ask;
Pertanyaan(int ratingStar, String ask) {
this.ratingStar = ratingStar;
this.ask = ask;
}
float getRatingStar() {
return 0;
}
void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
public String getAsk() {
return ask;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Pertanyaan> listPertanyaan;
ArrayAdapter<Pertanyaan> adapter2;
ProgressDialog pDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_view);
listPertanyaan = new ArrayList<>();
getpertanyaan get= new getpertanyaan();
get.execute();
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setAdapter(adapter2);
}
protected void onStart() {
super.onStart();
}
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list;
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();
}
#Override
protected Integer doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://flix.16mb.com/send_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
}
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
result += line;
}
}
if (is != null) {
is.close();
}
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
list.add(new Pertanyaan(0,jsonObject.getString("ask")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2.notifyDataSetChanged();
}
}
}
but when I run the app, the RatingBar is untouchable, just each list of ListView is touch however I want to tap the RatingBar.
did I doing something wrong? help me please.
EDIT :
item_listview.xml
<RatingBar
android:id="#+id/rate_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:numStars="5"
android:stepSize="1"
style="#style/Widget.AppCompat.RatingBar.Indicator" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold" />
the RatingBar is read-only because of the style you are using.
style="#style/Widget.AppCompat.RatingBar.Indicator"
sets the attribute android:isIndicator to true which makes behave it, in the way are experiencing. You can either get rid of the line, or try to force android:isIndicator to false in your item_listview.xml

First time SharedPreferences use with GridView

This is my Apps Screenshoot :
There is two button in that GridView : +/-.
So what im gonna try is when i press "+" button or "-" button, the quantity is store in SharedPreferences.
But really im confused about this.
This is my code so far :
package com.android.customer_blanjapasar.Utility;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.customer_blanjapasar.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Leon on 5/3/2016.
*/
public class CustomGridView2 extends BaseAdapter {
private ArrayList<ListItem> listData;
private LayoutInflater layoutInflater;
private Context context;
private String[] imageUrls;
private int count = 0;
int arrayCount[];
SharedPreferences prefs ;
SharedPreference sharedPreference;
public CustomGridView2(Context context, ArrayList<ListItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
this.context = context;
sharedPreference = new SharedPreference();
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.afterlogin_product_gridview, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.nama_produk);
holder.teaserView = (TextView) convertView.findViewById(R.id.harga);
holder.imageView = (ImageView) convertView.findViewById(R.id.img_produk);
holder.cmdMinus = (Button) convertView.findViewById(R.id.btn_min);
holder.cmdPlus = (Button) convertView.findViewById(R.id.btn_plus);
holder.qty = (TextView) convertView.findViewById(R.id.lbl_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListItem newsItem = listData.get(position);
String satuan = newsItem.getSatuan().toString();
String harga = newsItem.getReporterName().toString();
harga = "Rp. " + harga + " / " + satuan;
holder.headlineView.setText(newsItem.getHeadline().toUpperCase());
holder.teaserView.setText(harga);
String a = newsItem.getUrl();
holder.cmdPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = Integer.parseInt( holder.qty.getText().toString());
count++;
holder.qty.setText(""+count);
}
});
holder.cmdMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = Integer.parseInt( holder.qty.getText().toString());
if(count == 0) {
holder.qty.setText("0");
}
else {
count--;
holder.qty.setText("" + count);
}
}
});
if (holder.imageView != null) {
//new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
Picasso
.with(context)
.load(a)
.fit()
.into(holder.imageView);
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView teaserView;
ImageView imageView;
TextView satuan,qty;
Button cmdPlus,cmdMinus;
}
}
I already see this tutorial. But im still getting confused. Please guide me step by step.
EDIT
This is ListItem.class :
public class ListItem {
private String headline;
private String reporterName;
private String kode;
private String url;
private String satuan;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
public String getReporterName() {
return reporterName;
}
public void setReporterName(String reporterName) {
this.reporterName = reporterName;
}
public String getKode() {
return kode;
}
public void setKode(String kode) {
this.kode = kode;
}
public String getSatuan() {
return satuan;
}
public void setSatuan(String satuan) {
this.satuan = satuan;
}
#Override
public String toString() {
return "[ headline=" + headline + ", reporter Name=" + reporterName + " , date=" + kode + "]";
}
}
And this is the code inside MainActivity.class :
public class AfterLogin_Produk extends Activity {
Activity activity;
ImageButton btn_resep,btn_product;
static int jArray;
GridView product_gridview;
static String[] nama_prdct;
static String[] img_prdct;
static String[] harga_prdct;
static String[] satuan_prdct;
static String kode_ktgr;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.after_login_produk_main);
product_gridview = (GridView) findViewById(R.id.product_gridview);
new GetLength().execute();
}
public ArrayList<ListItem> getListData() {
ArrayList<ListItem> listMockData = new ArrayList<ListItem>();
for (int i = 0; i < jArray; i++) {
ListItem newsData = new ListItem();
newsData.setUrl(img_prdct[i]);
newsData.setHeadline(nama_prdct[i]);
newsData.setReporterName(harga_prdct[i]);
newsData.setSatuan(satuan_prdct[i]);
listMockData.add(newsData);
}
return listMockData;
}
class GetLength extends AsyncTask<String, String, String> {
String nama_product,img_product,harga_product,satuan_product;
JSONParser2 jParser = new JSONParser2();
ArrayList<String> list_nama_produk = new ArrayList<String>();
ArrayList<String> list_img_produk = new ArrayList<String>();
ArrayList<String> list_harga_produk = new ArrayList<String>();
ArrayList<String> list_satuan_produk = new ArrayList<String>();
protected String doInBackground(String... params) {
try {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("kode_kategori", kode_ktgr));
JSONObject json = jParser.makeHttpRequest("http:xxx.php", "POST", param);
JSONArray array = json.getJSONArray("categories");
jArray = array.length();
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
nama_product = row.getString("nama_produk");
img_product = row.getString("img_produk");
harga_product = row.getString("harga_satuan");
satuan_product = row.getString("nama_satuan");
list_nama_produk.add(nama_product);
list_img_produk.add(img_product);
list_harga_produk.add(harga_product);
list_satuan_produk.add(satuan_product);
}
} catch (Exception e) {
System.out.println("Exception : " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Toast.makeText(getBaseContext(),"Value : " + list_nama_kategori,Toast.LENGTH_SHORT).show();
nama_prdct = new String[list_nama_produk.size()];
img_prdct = new String[list_img_produk.size()];
harga_prdct = new String[list_harga_produk.size()];
satuan_prdct = new String[list_satuan_produk.size()];
nama_prdct = list_nama_produk.toArray(nama_prdct);
img_prdct = list_img_produk.toArray(img_prdct);
harga_prdct = list_harga_produk.toArray(harga_prdct);
satuan_prdct = list_satuan_produk.toArray(satuan_prdct);
ArrayList<ListItem> listData = getListData();
product_gridview.setAdapter(new CustomGridView2(AfterLogin_Produk.this, listData));
}
}
you are using custom array list of object than set propertie to it and on back press of application you can jsonify your object to string and store it in shared preference and at activity on create you can regenerate your object getting from shared preference. in activity onCreate()
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
(Dashboard.this);
String data = mSettings.getString("data", "");
/* Should Activity Check for Updates Now? */
if ((data.equals(""))) {
//do nothing data is not in shared preference
}
else {
//data is there convert To object
data=mSettings.getString("data", "");
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
ArrayList<ListRowItem> listRowItems = new Gson().fromJson(data, listType);
//setAdapter coming for arrayList as usual.
}
and in backPressed you can read data from adapter and jsonify it using json and put it in sharedPreference
i hope you understand the login . clear preference after data set.
Your issue is here:
holder.qty.setText(store);
It is clearly pointed out in your error log:
android.content.res.Resources$NotFoundException: String resource ID
0x1 at android.content.res.Resources.getText(Resources.java:1409) at android.widget.TextView.setText(TextView.java:4943)
store is an integer and setText is trying to look for a resource with this id. Use this instead.
holder.qty.setText(store.toString());
Also, to reduce the complexity of shared preferences specific code you can use this library

Android - Custom Adapter and AsyncTask

I have a custom adapter and I need to use it in onPostExecute method to populate a ListView with an image and a text.
This is the Custom Adapter
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class MyAdapter extends BaseAdapter {
private Activity mActivity;
private ArrayList listaElementi;
private static LayoutInflater infilater = null;
public MyAdapter( Activity a, ArrayList list) {
mActivity = a;
listaElementi = list;
infilater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listaElementi.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if( convertView == null )
vi = infilater.inflate(R.layout.riga, null);
TextView nome = (TextView) vi.findViewById(R.id.nome);
ImageView immagine = (ImageView) vi.findViewById(R.id.immagine);
Riga rigaCorrente = (Riga) listaElementi.get(position);
nome.setText(rigaCorrente.getNome());
immagine.setImageDrawable(mActivity.getResources().getDrawable(rigaCorrente.getImmagine()));
return vi;
}
}
This is my onPostExecute method:
private class LongOperation extends AsyncTask<String, String, JSONObject> {
//Other methods here
protected void onPostExecute(JSONObject result) {
JSONObject jobj = null;
JSONArray elenco_cartelle = null;
try {
jobj = new JSONObject(String.valueOf(result));
} catch (JSONException e) {
e.printStackTrace();
}
//Provo a recuperare i campi json
try {
elenco_cartelle = jobj.getJSONArray("elenco");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<Riga> arrayCartelle = new ArrayList<Riga>();
//DEvo scorrere le'elenco delle cartelle
for (int i = 0; i < elenco_cartelle.length(); i++) {
try {
String nome = elenco_cartelle.getString(i);
arrayCartelle.add( new Riga( nome , R.drawable.ic_launcher ) );
} catch (JSONException e) {
e.printStackTrace();
}
}
MyAdapter myAdapter = new MyAdapter(CartelleActivity.class,arrayCartelle);
mainListView.setAdapter(myAdapter);
// Close progress dialog
Dialog.dismiss();
}
}
And this is my Riga class
public class Riga {
String nome;
Integer idImmagine;
public Riga( String nome, Integer idImmagine ) {
super();
this.nome = nome;
this.idImmagine = idImmagine;
}
public String getNome() {
return this.nome;
}
public Integer getImmagine() {
return this.idImmagine;
}
public void setNome( String nome ) {
this.nome = nome;
}
public void setIdImmagine( Integer idImmagine ) {
this.idImmagine = idImmagine;
}
}
The problem is on this line:
MyAdapter myAdapter = new MyAdapter(CartelleActivity.class,arrayCartelle);
The IDE ( AndroidStudio ) says that I can't use CartelleActivity.
How can I use my Adapter?
SOLVED.
Used:
CartelleActivity.this
instead
CartelleActivity.class
Theres something fishy in your code. Try to define your ArrayList in your adapter by changing it to ArrayList<Riga> :
private Activity mActivity;
private ArrayList<Riga> listaElementi;
private static LayoutInflater infilater = null;
public MyAdapter( Activity a, ArrayList<Riga> list) {
mActivity = a;
listaElementi = list;
infilater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public class LongOperation extends AsyncTask<String, String, JSONObject> {
private Activity a;
public CustomAsync(Activity a) {
this.a = a;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
MyAdapter myAdapter = new MyAdapter(a, new ArrayList());
}
}

on Click of text View inside a List Item not getting proper value

I have a ListView ,In that each ListItem having some items(textViews),In which one textView is having click event.That I have put in my custom adater,And I am calling an asynctask on its cLick event,For that I want a value when I click on that textView its "queID" I want,But currently I am gettong it null..Please see my code and help me please..!
"qoute" is that textView.On which I have put click event.how to set"buyer_req_Id" and get tag on it?I currrently successfully get the tag on each "ListItem" Click event ,I want to set the same tag on ListItem's textView.Inside java class I have put only adapter,In which I want "buyer_request_id".
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
java class(asynctask)
public class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
scr_post.setVisibility(View.GONE);
scr_view.setVisibility(View.GONE);
quote_view.setVisibility(View.VISIBLE);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// String query = "?customer_id=" +
// Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "")
// + "&buyer_request_id=23";
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + buyer_request_id;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyerID = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyerID);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyerID);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
queList.add(quote);
System.out.println(":::::::::::::Buyer request ID:" + buyerID);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
quoteAdapter = new QuoteAdapter(BuyingreqActivity.this, queList);
quoteList.setAdapter(quoteAdapter);
}
}
// Try this way,hope this will help you...
localViewholder.quote.setTag(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
String buyerId = v.getTag().toString(); // user this buyerId for your requirement
System.out.println("Buyer Id Is "+buyerId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
I have solved my problem as below by changing my asynctask to void to string :
adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> reqList) {
this.mContext = paramContext;
this.BuyingRequestArray = reqList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
/* localViewholder.quote.setTag(localViewholder); */
} else {
localViewholder = (Viewholder) paramView.getTag();
/* localViewholder.quote = ((TextView) paramView.getTag()); */
}
final String reqId = BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println("::::::::::::::My reqId:::::::::::" + reqId);
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
System.out.println("Buyer Id Is " + reqId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute(reqId);
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}

Categories

Resources