Not able to send data to server on clicking button? - android

public class PubHer extends Fragment{
EditText eCont;
Spinner spinnerareas3, spinnerareas4;
Button publish, switchArea;
static Context con;
String ite, cont, sno=""+12;
private Context globalContext = null;
public int item1, item2;
public static void fun(Context c) {
con = c;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pubher, container, false);
spinnerareas3 = (Spinner) rootView.findViewById(R.id.spinnerplan1);
// ListView list = (ListView) rootView.getl
spinnerareas4 = (Spinner) rootView.findViewById(R.id.spinnerplan2);
// spinnerareas3.setOnItemSelectedListener();
spinnerareas3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item1 = position;
ite = ""+parent.getSelectedItemPosition();
CharSequence charS = item1+"";
Toast.makeText(con ,charS , Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerareas4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item2 = position;
CharSequence charS = item2+"";
Toast.makeText(con ,charS , Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
publish = (Button) rootView.findViewById(R.id.bPublish);
publish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cont = eCont.getText().toString();
upload();
}
});
switchArea = (Button) rootView.findViewById(R.id.bJumper);
switchArea.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateDetail();
}
private void updateDetail() {
// TODO Auto-generated method stub
Intent i = new Intent("com.example.notifier.JumpList");
startActivity(i);
}
});
return rootView;
}
protected void upload() {
// TODO Auto-generated method stub
if(item2==0)
new Sync_upload_event_info(this.getActivity(), 0).execute(sno,ite,cont);
else if(item2==1)
new Sync_upload_adver_info(this.getActivity(),0).execute(sno,ite,cont);
else
new Sync_upload_emer_info(this.getActivity(),0).execute(sno,ite,cont);
}
}
And this is my one of the sync files to server
public class Sync_upload_event_info extends AsyncTask{
private Context context;
String sno, place_id, event_text;
public Sync_upload_event_info(Context context,int flag)
{
context=this.context;
int getorpost=flag;
}
protected void onPreExecute(){ }
#Override
protected String doInBackground(String... arg0)
{
try{
sno = (String)arg0[0];
place_id = (String)arg0[1];
event_text = (String)arg0[2];
String link = "http://notifiermmn.site50.net/upload_event_info.php?sno="+sno+"&place_id="+place_id+"&event_text="+event_text;
link=link.replaceAll(" ", "%20");
System.out.println("LINK:"+link);
//URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
//request.setURI(new URI(link));
HttpResponse response = client.execute(new HttpGet(link));
return "";
}
catch(Exception e)
{
return new String("Exception: " + e.getMessage());
}
}
protected void onPostExecute(String result){
}
}
as soon as I press the publish button and set the spinner 4 to event ie Sync_upload_event_info or other two My app gets crashed.
the logcat is also indicating to the publish button click handling but not able to resolve

I think you forget to create reference of eCont EditText like:
EditText eCont= (EditText)rootView.findViewById(R.id.cont);
Your app crashed it's bacause eCont is NULL in your publish button Click event.

Related

Filtered ListView onItemClick returns Item at original position for online Activities

Hi I am trying to make a apps that contains some list item with auto suggestion from a website. but when i Click one of the Item it return only first item related value. But i want only related value from them.
This is my Main Activity:
public class MainActivity extends AppCompatActivity {
ListView vl;
Button b;
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> news_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vl = (ListView) findViewById(R.id.myList);
b= (Button) findViewById(R.id.addNewbutton);
inputSearch = (EditText) findViewById(R.id.inputSerach);
fetchingData();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddingNews.class));
}
});
}
void fetchingData(){
String myURL = "http://192.168.56.1/android/api/gettingnews.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(myURL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
final String[] news_title = new String[response.length()];
final String[] news_detail = new String[response.length()];
final String[] news_time = new String[response.length()];
for (int i =0; i < response.length(); i++){
try {
JSONObject jsonObject = (JSONObject) response.get(i);
news_title[i] = jsonObject.getString("title");
news_detail[i] = jsonObject.getString("news");
news_time[i] = jsonObject.getString("time");
} catch (JSONException e) {
e.printStackTrace();
}
}
// vl.setAdapter(new ArrayAdapter(getApplicationContext(), R.layout.mylistview, R.id.textViewforlist, news_title));
// Adding items to listview
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.mylistview, R.id.textViewforlist, news_title);
vl.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
vl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Details.class);
intent.putExtra("MyTitle", news_title[position]);
intent.putExtra("MyNews", news_detail[position]);
intent.putExtra("MyTime", news_time[position]);
startActivity(intent);
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley Log", error);
}
});
com.example.forkan.tuntuninews.AppController.getInstance().addToRequestQueue(jsonArrayRequest);
Toast.makeText(getApplicationContext(),"Data Loaded Successfully", Toast.LENGTH_LONG).show();
}
}
and this is My Details: activites;
public class Details extends AppCompatActivity {
TextView title, time, details;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
title = (TextView) findViewById(R.id.mytitle);
time = (TextView) findViewById(R.id.mytime);
details = (TextView) findViewById(R.id.mydetail);
String _title = getIntent().getStringExtra("MyTitle");
String _news = getIntent().getStringExtra("MyNews");
String _time = getIntent().getStringExtra("MyTime");
title.setText(_title);
time.setText(_time+"\n\n");
details.setText(_news);
}
}
How Can i Fix it Please Help me..

how can i pass the image URL from activity to Alert Dialog box as a imageview?

Here is my CartRowHolder
class CartRowHolder {
ImageView icon;
TextView txtprice,txttitle,personalize;
TextView txtquantity;
ImageView imgdelete,imgedit,image;
public CartRowHolder(View v) {
icon=(ImageView)v.findViewById(R.id.imageicon);
txtprice=(TextView)v.findViewById(R.id.txtoprice);
txttitle=(TextView)v.findViewById(R.id.txtotitle);
txtquantity=(TextView)v.findViewById(R.id.txtoquantity);
personalize=(TextView)v.findViewById(R.id.txtpersonalize);
imgdelete=(ImageView)v.findViewById(R.id.imgdelete);
imgedit=(ImageView)v.findViewById(R.id.edit);
}
}
Now in the ListView a ImageView and Delete Button, Edit button is there So as i click on the Edit a Dialogbox is open and in the Dialogbox i want to pass the imageView.....and i have the ImageUrl
class CartAdapter extends BaseAdapter {
Activity activity;
List<CartItem> cartItemList;
ImageLoader imageLoader;
LayoutInflater layoutInflater;
CartItem cartItem;
AppPreferenceManager appPreferenceManager;
public CartAdapter(Activity activity,List<CartItem>cartItemList) {
this.activity=activity;
this.cartItemList=cartItemList;
appPreferenceManager=new AppPreferenceManager(activity);
}
public int getCount() {
return cartItemList.size();
}
#Override
public Object getItem(int position) {
return cartItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
cartItem=cartItemList.get(position);
CartRowHolder cartRowHolder;
Bundle extras = getIntent().getExtras();
TextView tk;
if (extras != null) {
}
if(imageLoader==null) {
imageLoader=new ImageLoader(activity);
}
if(layoutInflater==null) {
layoutInflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null) {
convertView=layoutInflater.inflate(R.layout.order_row,null);
cartRowHolder=new CartRowHolder(convertView);
cartRowHolder.imgdelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CartItem cartItem=cartItemList.get(position);
deletCartItem(cartItem.getPid());
}
});
cartRowHolder.imgedit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CartItem cartItem=cartItemList.get(position);
ImageView image;
final EditText personalise;
Button update;
final TextView quan,title1;
final ImageButton plusd,minusd;
final AlertDialog alertDialog;
View view=getLayoutInflater().inflate(R.layout.activity_edit,null);
final AlertDialog.Builder builder=new AlertDialog.Builder(CartActivity.this).setView(view);
update = (Button)view.findViewById(R.id.update);
quan=(TextView)view.findViewById(R.id.quan);
minusd=(ImageButton)view.findViewById(R.id.minus);
plusd=(ImageButton)view.findViewById(R.id.plus);
alertDialog=builder.create();
title1=(TextView)view.findViewById(R.id.TitleView);
title1.setText(cartItemList.get(position).getName());
personalise=(EditText)view.findViewById(R.id.editpersonalize);
personalise.setText(cartItemList.get(position).getPersonalize());
quan.setText(cartItemList.get(position).getQunatity());
image=(ImageView)view.findViewById(R.id.image1);
//imageLoader.DisplayImage(Bitmap.get);
final int num=Integer.parseInt(quan.getText().toString());
final int[] counter = {num};
plusd.setOnClickListener(new View.OnClickListener() {
//int counter=0;
#Override
public void onClick(View v) {
//Toast.makeText(CartActivity.this, "Positive is click", Toast.LENGTH_SHORT).show();
counter[0]++;
quan.setText(""+ counter[0]);
minusd.setClickable(true);
plusd.setClickable(true);
if(counter[0] ==10){
plusd.setClickable(false);
minusd.setClickable(true);
Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(SingleItem_Activity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
if(counter[0] >=10) {
plusd.setClickable(false);
minusd.setClickable(true);
Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
}
}
});
minusd.setOnClickListener(new View.OnClickListener() {
// int counter=0;
#Override
public void onClick(View v) {
if(counter[0] ==1) {
minusd.setClickable(false);
}
else{
counter[0] = counter[0] -1;
quan.setText(""+ counter[0]);
if(counter[0] <=1){
minusd.setClickable(false);
plusd.setClickable(true);}
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String update_quan=quan.getText().toString();
String update_personalise = personalise.getText().toString();
updateCartItem(update_quan,cartItem.getPid(),update_personalise);
//Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
cartRowHolder.txttitle.setText(cartItem.getName());
cartRowHolder.txtprice.setText(cartItem.getSubtotal());
cartRowHolder.txtquantity.setText(cartItem.getQunatity());
cartRowHolder.personalize.setText(cartItem.getPersonalize());
imageLoader.DisplayImage(cartItem.getImage(), cartRowHolder.icon);
}
return convertView;
}
OK, you will need to following code:
1) add permission for internet in your manifest
<uses-permission android:name="android.permission.INTERNET" />
2) You will need to update your list adapter
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
3) update your mainactivity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
_adapter = new PersonAdapter(this, _data);
_listView.setAdapter(_adapter);
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
4) custom image layout
<?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="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/image"/>
</LinearLayout>
A bit of explanation:
there is an interface between the activity and the list adapter (IDialog)
as part of the data, each item(person) has a field URL, when the user is clicking on the button, the activity is "notified" by the interface and downloading the appropriate image and showing it in the dialog
After so any hour I find out the Soloution. Now In the Dialog-box i can again download the image.....
imageFileURL="url";
String imageFileURL=cartItemList.get(position).getImage();
try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.connect();
InputStream inputStream = httpConn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
image.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Progress dialog not showing in button click event in listview

I have a button in each list item of list view. In that button click event i have some codes to run. In click event im showing the progress dialog before the code runs. but its not getting shown. After all the codes in click event completes in the end progress dialog gets shown. Plz help me.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
TheListViewM = (ListView) findViewById(R.id.lvItems);
ImageAdapter anImageAdapterM =new ImageAdapter(this);
TheListViewM.setAdapter(anImageAdapterM);
}
public class ImageAdapter extends BaseAdapter {
private Context mContextL;
public ImageAdapter(Context contextP) {
mContextL = contextP;
}
public int getCount() {
return ItemList.GetLength();
}
public Object getItem(int PositionP) {
return ItemList.GetObject(PositionP);
}
public long getItemId(int PositionP) {
return PositionP;
}
public View getView(final int PositionP, View ConvertViewP, ViewGroup ParentP) {
if (ConvertViewP == null) {
LayoutInflater inflater = (LayoutInflater) mContextL.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ConvertViewP = inflater.inflate(R.layout.add_cart_row_layout, ParentP, false);
}
TextView textView1 = (TextView) ConvertViewP.findViewById(R.id.tvName);
textView1.setText("asdfg");
final Spinner spQuantity = (Spinner) ConvertViewP.findViewById(R.id.spQuantity);
spQuantity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> Parent, View view,
int pos, long id) {
ProgressDialog aProgressDialogL = new ProgressDialog(mContextL);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show();
//Processiing codes
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayAdapter<String> QuantityAdapter1 = new ArrayAdapter<String>(mContextL,android.R.layout.simple_spinner_item, QuantityList);
QuantityAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spQuantity.setAdapter(QuantityAdapter1);
Button btn1 = (Button) ConvertViewP.findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProgressDialog aProgressDialogL = new ProgressDialog(activity1.this);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show(); }
});
return ConvertViewP;
}
Try this one.
public class ImageAdapter extends BaseAdapter {
private Context mContextL;
public ImageAdapter(Context contextP) {
mContextL = contextP;
}
public int getCount() {
return ItemList.GetLength();
}
public Object getItem(int PositionP) {
return ItemList.GetObject(PositionP);
}
public long getItemId(int PositionP) {
return PositionP;
}
class ViewHolder {
Button btn1;
TextView textView1;
Spinner spQuantity;
}
public View getView(final int PositionP, View ConvertViewP, ViewGroup ParentP) {
ViewHolder holder;
if (ConvertViewP == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContextL.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ConvertViewP = inflater.inflate(R.layout.add_cart_row_layout, ParentP, false);
holder.textView1 = (TextView) ConvertViewP.findViewById(R.id.tvName);
holder.spQuantity = (Spinner) ConvertViewP.findViewById(R.id.spQuantity);
holder.btn1 = (Button) ConvertViewP.findViewById(R.id.btn1);
ConvertViewP.setTag(holder);
}
else{
holder = (ViewHolder) ConvertViewP.getTag();
}
holder.textView1.setText("asdfg");
holder.spQuantity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> Parent, View view,
int pos, long id) {
ProgressDialog aProgressDialogL = new ProgressDialog(mContextL);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show();
//Processiing codes
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayAdapter<String> QuantityAdapter1 = new ArrayAdapter<String>(mContextL,android.R.layout.simple_spinner_item, QuantityList);
QuantityAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spQuantity.setAdapter(QuantityAdapter1);
holder.btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProgressDialog aProgressDialogL = new ProgressDialog(activity1.this);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show(); }
});
return ConvertViewP;
}
}

custom listview edit value

i have EditText in second activity.so the value enter here will be added to the custom listview in first activity.
i first activity in list i have textview,checkbox and button(edit). here textview will be from second activity edittext data. so here if i click on edit then it navigates to second activity of that particular data .am getting all these now .. in second acitity i want to edit the textfield value .so it has to display the edited value with this data in listview of particular row.
public class MyApplication extends Application{
ArrayList<String> arryList = new ArrayList<String>();
String cardNumberData=null;
}
public class Second extends Activity{
EditText cardNumber;
String cardNumberReceived;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.editcredit);
cardNumberReceived = getIntent().getStringExtra("cardwithoutstring");
System.out.println("cardWithOutStringReceived"+cardNumberReceived);
app = ((MyApplication) getApplicationContext());
cardNumber =(EditText)findViewById(R.id.cardnumber);
cardNumber.setText(cardNumberReceived);
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
app.cardNumberData =cardNumber.getText().toString();
System.out.println("Gotcardname"+app.cardNumberData);
app.arryList.add(app.cardNumberData);
System.out.println("Array List Size "+app.arryList.size());
System.out.println("Array List Size "+app.cardTypeList.size());
Intent saveIntent =new Intent(Second.this,First.class);
startActivity(saveIntent);
}
});
}
}
public class First extends Activity{
protected ListItemsState[] mDeletedItemsStates;
protected ArrayAdapter<ListItemsState> mListAdapter;
protected ListView mFoldersListView;
protected Context mContext;
LayoutInflater lay;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newcard);
app = ((MyApplication) getApplicationContext());
mDeletedItemsStates = (ListItemsState[])getLastNonConfigurationInstance();
if (mDeletedItemsStates == null) {
mDeletedItemsStates = new ListItemsState[app.arryList.size()];
for (int i = 0; i < app.arryList.size(); i++) {
mDeletedItemsStates[i] = new ListItemsState(app.arryList.get(i),i);
}
}
ArrayList<ListItemsState> gridItemsList = new ArrayList<ListItemsState>();
gridItemsList.addAll(Arrays.asList(mDeletedItemsStates));
mListAdapter = new DeletedItemsStateArrayAdapter(this, gridItemsList);
mFoldersListView.setAdapter(mListAdapter);
mFoldersListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mFoldersListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "am thelist",
Toast.LENGTH_LONG).show();
}
});
}
private static class ListItemsState {
private String produ = "";
private boolean checked = false;
private int position;
public ListItemsState(String produ, int position) {
this.position = position;
}
public String getProdu() {
return produ;
}
public int getPosition() {
return position;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
/** Holds child views for one row. */
private static class ListItemsStateViewHolder {
private RadioButton checkBox;
private TextView produ;
private Button edit;
public TextView getProdu() {
return produ;
}
public Button getEdit() {
return edit;
}
public RadioButton getCheckBox() {
return checkBox;
}
}
private class DeletedItemsStateArrayAdapter extends
ArrayAdapter<ListItemsState> {
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private LayoutInflater inflater;
public DeletedItemsStateArrayAdapter(Context context,
List<ListItemsState> sentItemsStateList) {
super(context, R.layout.customlist, R.id.card,
sentItemsStateList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ListItemsState deletedItemsState = (ListItemsState) this
.getItem(position);
ListItemsStateViewHolder viewHolder = new ListItemsStateViewHolder();
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.customlist, null);
convertView.setTag(new ListItemsStateViewHolder());
}
else {
viewHolder = (ListItemsStateViewHolder) convertView.getTag();
viewHolder.checkBox = viewHolder.getCheckBox();
viewHolder.produ = viewHolder.getProdu();
viewHolder.edit = viewHolder.getEdit();
}
viewHolder.produ = (TextView) convertView.findViewById(R.id.card);
viewHolder.checkBox = (RadioButton) convertView.findViewById(R.id.radioButton1);
viewHolder.edit=(Button)convertView.findViewById(R.id.editbutton);
try {
viewHolder.checkBox.setTag(deletedItemsState);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
viewHolder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent edit =new Intent(getApplicationContext(), Second.class);
edit.putExtra("cardNumberSending",app.arryList.get(position));
edit.putExtra("Indexvalue",mFoldersListView.getItemIdAtPosition(position));
System.out.println("Index value ::::::::: "+mFoldersListView.getItemIdAtPosition(position));
startActivity(edit);
}
});
viewHolder.produ.setText(deletedItemsState.getProdu());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return mDeletedItemsStates;
}
}
You are adding the edited data to the ArrayList Again avoid it inside the Second Activity
app.cardNumberData = cardNumber.getText().toString();
if(arryList.indexOf(cardNumberReceived) != -1)
{
app.arryList.set(arryList.indexOf(cardNumberReceived), app.cardNumberData);
}else
{
app.arryList.add(app.cardNumberData);
}
In your second Activity do this onClick of save.

How to Sort JSON Array by its Object Attribute on a ListActivity?

I implement a JSONArray to populate a ListView. Now I want to sort the items on the ListActivity alphabetically by its name, which is its Object Attribute.
How am I able to sort it out?
Heres the Object class I use to implement the ListView:
public class VideoLocation {
public String deleted_at = null;
public int documentary_video_length = -1;
public int id = -1;
public double latitude = 0d;
public double longitude = 0d;
public int position = -1;
public String updated_at = null;
public String name = null;
public String text = null;
public String documentary_video_url = null;
public String documentary_thumbnail_url = null;
public String audio_text_url = null;
public Footage[] footages = null;
public VideoLocation(){
}
and here's the ListActivity Class:
public class ProjectsList extends ListActivity implements OnItemClickListener, VideoLocationReceiver{
/** Called when the activity is first created. */
private VideoLocation[] videoLocations = null;
private VideoLocationAdapter videoLocationAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_list);
doSync();
//storeSharedPrefs();
ListView lv = getListView();
lv.setOnItemClickListener(this);
videoLocationAdapter = new VideoLocationAdapter(ProjectsList.this,
R.layout.listitems,
new VideoLocation[0]);
lv.setAdapter(videoLocationAdapter);
//CREATE VideoLocation[] from Database!
JsonDB dbhelper = new JsonDB(ProjectsList.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
db.beginTransaction();
videoLocations = dbhelper.getVideoLocations(db);
db.setTransactionSuccessful();//end transaction
db.endTransaction();
db.close();
}
#Override
public void onResume(){
super.onResume();
DBSync.setVideoLocationReceiver(ProjectsList.this);
}
#Override
public void onPause(){
super.onResume();
DBSync.setVideoLocationReceiver(null);
}
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Intent listIntent = new Intent(this, ProjectDetailsActivity.class);
VideoLocation vidLocation = videoLocations[position];
listIntent.putExtra("documentary_video_url",vidLocation.documentary_video_url);
startActivity(listIntent);
}
protected void storeSharedPrefs() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean("first-time", true)) {
doSync();
prefs.edit().putBoolean("first-time", false).commit(); // record the fact that the app has been started at least once
}
}
void doSync() {
Intent serviceIntent = new Intent(this, DBSync.class);
startService(serviceIntent);
}
public class VideoLocationAdapter extends ArrayAdapter<VideoLocation> {
public ImageLoader imageLoader;
ImageLoader loader = null;
public VideoLocationAdapter(Context context, int resource, VideoLocation[] vidLocs) {
super(context, resource, vidLocs);
ProjectsList.this.videoLocations = vidLocs;
loader = new ImageLoader(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = ProjectsList.this.getLayoutInflater().inflate(R.layout.listitems, null, true);
}
VideoLocation vidLocation = videoLocations[position];
ImageView v = (ImageView)convertView.findViewById(R.id.image);
String url = vidLocation.documentary_thumbnail_url;
v.setTag(url);
loader.DisplayImage(url, ProjectsList.this, v);
TextView titleView = (TextView)convertView.findViewById(R.id.txt_title);
titleView.setText(vidLocation.name);
return convertView;
}
#Override
public int getCount(){
return videoLocations==null?0:videoLocations.length;
}
#Override
public VideoLocation getItem(int position){
return videoLocations[position];
}
#Override
public boolean hasStableIds(){
return true;
}
#Override
public boolean isEnabled(int position){
return true;
}
#Override
public long getItemId(int position){
return videoLocations[position].id;
}
public void setVideoLocationData(VideoLocation[] newData){
ProjectsList.this.videoLocations = newData;
VideoLocationAdapter.this.notifyDataSetChanged();
}
}
#Override
public void receivedVideoLocationData(VideoLocation[] vidLocs) {
final VideoLocation[] locs = vidLocs;
if (vidLocs==null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//show popup and inform about missing network
}
});
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
videoLocationAdapter.setVideoLocationData(locs);
Log.d("ProjectsList", "updating video locations...");
}
});
}
}
}
Use Collections.sort. Parse your json and fill up a vector or an ArrayList (I think) with instance of VideoLocation. Then call Collections.sort.
Edit:
Collections.sort(youarrayList, new Comparator<VideoLocation>() {
#Override
public int compare(VideoLocation lhs, VideoLocation rhs) {
return lhs.name.compareTo(rhs.name);
}
});
In getVideoLocations(db), you may tell your query to return result as sorted by using ORDER BY [Column]

Categories

Resources