In my activity I am adding a header button to save the values of a listview, with an EditText and post them to a php/mysql web app.
I am able to get the values of the listview if I use setOnItemClickListener but when I use setOnClickListener on the header save button, I am not able to iterate through the listview.
I am using a custom array adaptor :-
public class CustomOrderAdaptor extends ArrayAdapter{
int groupid;
ArrayList<OneOrder> records;
Context context;
public CustomOrderAdaptor(Context context, int vg, int id, ArrayList<OneOrder>records) {
super(context, vg, id, records);
this.context = context;
groupid = vg;
this.records = records;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(groupid, parent, false);
TextView textName = (TextView) itemView.findViewById(R.id.product_name);
textName.setText(records.get(position).getproduct_name());
EditText new_quantity = (EditText) itemView.findViewById(R.id.new_quantity);
new_quantity.setText(records.get(position).getnew_quantity());
TextView textOrderitemid = (TextView) itemView.findViewById(R.id.order_item_id);
textOrderitemid.setText(records.get(position).getorder_item_id());
TextView textQuantity = (TextView) itemView.findViewById(R.id.quantity);
textQuantity.setText(records.get(position).getquantity());
return itemView;
}
}
data model :-
public class OneOrder {
private String quantity;
private String new_quantity;
private String product_name;
private String order_item_id;
public void setquantity(String quantity){this.quantity=quantity;}
public void setnew_quantity(String new_quantity){this.new_quantity=new_quantity;}
public void setproduct_name(String product_name){this.product_name=product_name;}
public void setorder_item_id(String order_item_id){this.order_item_id=order_item_id;}
public String getquantity(){return quantity;}
public String getnew_quantity(){return new_quantity;}
public String getproduct_name(){return product_name;}
public String getorder_item_id(){return order_item_id;}
}
My activity is :-
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_order);
context = this;
records = new ArrayList<OneOrder>();
listOrder = (ListView) findViewById(R.id.order_item_list);
LayoutInflater inflater = LayoutInflater.from(this);
View nTop = inflater.inflate(R.layout.activity_get_order_footer, null);
listOrder.addHeaderView(nTop);
adapter = new CustomOrderAdaptor(context, R.layout.list_order, R.id.product_name,
records);
listOrder.setAdapter(adapter);
Button mButton = (Button) nTop.findViewById(R.id.button_save);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONObject order_items = new JSONObject();
JSONObject sendObject = new JSONObject();
for (int i=0;i<adapter.getCount();i++){
JSONObject order_item = new JSONObject();
OneOrder current_order = (OneOrder) listOrder.getAdapter().getItem(i);
//OneOrder current_order = (OneOrder) getListView().getItemAtPosition(i);
try {
order_item.put("quantity", current_order.getquantity().toString());
order_item.put("new_quantity", current_order.getnew_quantity().toString());
order_item.put("order_item_id", current_order.getorder_item_id().toString());
order_items.put(String.valueOf(i),order_item);
} catch (JSONException e) {
e.printStackTrace();
}
}
HttpURLConnection conn = null;
try {
Intent i = getIntent(); // gets the previously created intent
String order_id = i.getStringExtra("order_id");
sendObject.put("items", order_items.toString());
sendObject.put("order_id", order_id);
try {
URL url = new URL("http://192.168.0.70/steam_dos/index.php?option=com_steam§ion=linen&task=save_order_out");
String message = sendObject.toString();
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 10000 /*milliseconds*/ );
conn.setConnectTimeout( 15000 /* milliseconds */ );
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
//make some HTTP header nicety
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
BufferedOutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();
//do something with response
InputStream is = conn.getInputStream();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
the error is here :-
order_item.put("quantity", current_order.getquantity().toString());
the error is simple :-
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String au.com.southportsteamlaundry.rfid.steamscanadditions.OneOrder.getquantity()' on a null object reference
The view looks like this :-
Layout view
I am trying to save all of the values of the listview after the save button is clicked but I am not getting the listview items with that code, could you please explain the best way to achieve that ? Thanks.
Normally it's not recommended to use Edit text with adapter, the reason is edit text saving cannot be handled when it scroll out.
There are two kinds solution.
Replace the listview with scrollview
2 create a variable and add a TextWatcher on the edittext. Whenever the edittext get modified, the text watcher detect the change and override the variable whener you done something on it.
code would be like
Implementing Text Watcher for EditText
my answer may not be the best one, but this is what I implemented to get the EditText values of the list view :
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONObject order_item = new JSONObject();
order_items_edited = new JSONObject();
for (int i = 0; i < listOrder.getCount(); i++) {
EditText et = (EditText) listOrder.getChildAt(i).findViewById(R.id.new_quantity);
if (et!=null) {
TextView oi = (TextView) listOrder.getChildAt(i).findViewById(R.id.order_item_id);
Log.i("dtag", "et is " + String.valueOf(et.getText()));
Log.i("dtag", "oi is " + String.valueOf(oi.getText()));
try {
order_item.put("new_quantity", String.valueOf(et.getText()));
order_item.put("order_item_id", String.valueOf(oi.getText()));
order_items_edited.put(String.valueOf(i),order_item);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
the main issue I was having was a null object for et, which is valid, but I wasn't testing for it.
Now its working, I will look at implementing a cleaner solution.
Related
I am dynamically adding views to my layout by using layout inflater, but I am trying to add an id to every new view that gets added so I can use a getter to extract the information.
I am also trying to change the array data in the new spinner that gets added in each view as it is currently showing the default string array and not the array that I read from my database
public void onAddField(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.field, null);
// Add the new row before the add field button.
getdata2();
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
Log.d(String.valueOf(rowView.getId()), "onAddField: ");
getdata2();
}
private void getdata2() {
StringRequest stringRequest = new StringRequest("http://.../getDataCategories.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
catdetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void catdetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList2.add(json.getString(CategoryType_idArray));
} catch (JSONException e) {
e.printStackTrace();
}
}
type2_workout_mySpinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, arrayList2));
}
You can add id as tag inside view object
View rowView = inflater.inflate(R.layout.field, null);
rowView.setTag(1);
consider number as your view id and get this id as getTag().
You can also update the array data and spinner update using above.
Like get a child from parentLinearLayout using parentLinearLayout.getchildAt() and then get the spinner from view and the again set adapter into the spinner.
I have a spinner that gets populated from a text file stored on a web server. The contents of this text file are then stored in an ArrayList. My app is going to have the user add an item to this text file that they name themselves and therefore update the spinner. What I need to be able to do is have the spinner do something when an item is selected. As the user can give any name to an item they add, how can my app do something when that particular item is selected from the spinner if it doesn't know what they named it?
Right now I have my app set up so that if spinner item equals "string" do this... but this obviously won't work if the user has named an item themselves. I hope I have explained my question ok! This is my code so far:
public class MainActivity extends AppCompatActivity {
String statusLink = "http://redacted.uk/pmt/status.txt";
String deviceLink = "http://redacted.uk/pmt/devices.txt";
String status;
final String degree = "\u00b0";
ArrayList<String> devicesAL = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Set up connection to device.txt on web server
URL deviceUrl = new URL (deviceLink);
URLConnection deviceConn = deviceUrl.openConnection();
deviceConn.setDoOutput(true);
deviceConn.connect();
InputStream dis = deviceConn.getInputStream();
InputStreamReader disr = new InputStreamReader(dis, "UTF-8");
BufferedReader dbr = new BufferedReader(disr);
String deviceLine;
// Set up connection to status.txt on web server
URL statusUrl = new URL(statusLink);
URLConnection statusConn = statusUrl.openConnection();
statusConn.setDoOutput(true);
statusConn.connect();
InputStream sis = statusConn.getInputStream();
InputStreamReader sisr = new InputStreamReader(sis, "UTF-8");
BufferedReader sbr = new BufferedReader(sisr);
String statusLine;
try {
while ((deviceLine = dbr.readLine()) != null) {
//System.out.println(deviceLine);
devicesAL.add(deviceLine);
for (String str : devicesAL) {
System.out.println(str);
}
}
while ((statusLine = sbr.readLine()) != null) {
System.out.println(statusLine);
status = statusLine;
System.out.println("Status = " + status);
TextView output = (TextView) findViewById(R.id.textView);
System.out.println(status);
}
for (String str : devicesAL) {
System.out.println(str);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//LOAD SPINNER
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adp = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, devicesAL);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adp);
adp.notifyDataSetChanged();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView output = (TextView) findViewById(R.id.textView);
if (parent.getItemAtPosition(position).equals("Water Cooler")) {
System.out.println("Water cooler selected");
output.setText(status);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
});
} finally {
sbr.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
Since you say you want to :
If the user then selects "fridge" from the spinner, the data inside fridge.txt gets displayed
So i think you can just get the file name from the spinner then show the content. It will be like this :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedFileName = parent.getItemAtPosition(position);
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, selectedFileName+".txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {}
TextView tvText = (TextView)findViewById(R.id.tvText);
tvText.setText(text.toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
i am trying to send Data (ID value) from one activity to other
but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code
public class Order extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
new JSONTask().execute("http://146.185.178.83/resttest/order");
}
public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<OrderModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<OrderModel> orderModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
orderModelList.add(orderModel);
}
return orderModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<OrderModel> result) {
super.onPostExecute(result);
dialog.dismiss();
OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
lvUsers.setAdapter(adapter);
}
}
public class OrderAdapter extends ArrayAdapter {
public List<OrderModel> orderModelList;
private int resource;
private LayoutInflater inflater;
public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
super(context, resource, objects);
orderModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
final int orderId = orderModelList.get(position).getId();
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderId);
startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
private Button bOrderNo;
}
}
}
The holder gets executed in loop i guess is why it wouldn't send right Id.
How do i get it to send only Id of the clicked orderId
you can check this link to see how json Response looks like http://146.185.178.83/resttest/order
You have a silly mistake in your code . I have edited single line in your code . I think you are getting same "orderId" every time instead of actual "orderId". Check this one . I hope your problem will resolve .
final int index = position;
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderModelList.get(index).getId());
startActivity(intent);
}
});
Please try
In place of
intent.putExtra("parameter_name", orderId);
Please put
intent.putExtra("parameter_name", orderModelList.get(position).getId());
I have these two activities in my Android application in which the first one is where the user will enter the asked information (to a edittext) and the other one is where it will send the data (I used putExtra to transfer the data from the 1st activity to the 2nd) to the MySQL database and will later on display results in ListView. The problem is, when the 2nd activity starts (considering that I have already entered something on the first activity) and after the progress dialog shows, there is nothing being displayed, or the results don't appear. But when I tried just starting the second activity (the edittext in the 1st activity is null) it shows the results. I'm not sure if what causes the problem, is on the application or in the PHP file I used in fetching the data?
Here are the codes:
MainActivity.java
//first activity
public class SearchFragment extends Fragment implements View.OnClickListener {
Button butt;
EditText destination;
String d;
public SearchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
butt = (Button) view.findViewById(R.id.searchBUTTon);
butt.setOnClickListener(this);
destination = (EditText) view.findViewById(R.id.destinationTO);
return view;
}
#Override
public void onClick(View v) {
d = destination.getText().toString();
Intent a = new Intent(getActivity(), SearchResultsActivity.class);
a.putExtra("to", d);
startActivity(a);
}
}
SearchResultsAcivity.java
//second activity
public class SearchResultsActivity extends AppCompatActivity implements ListView.OnItemClickListener {
private ListView listView;
private String JSON_STRING;
String destination;
TextView d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
Intent a = getIntent();
destination = a.getStringExtra("to");
d = (TextView) findViewById(R.id.textView3);
d.setText(destination);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
}
private void showBusList() {
JSONObject jsonObject = null;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(config.TAG_JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
//get strings
String id = jo.getString(config.TAG_ID);
String busName = jo.getString(config.TAG_BUSNAME);
String terminal = jo.getString(config.TAG_TERMINAL);
HashMap<String, String> busDetails = new HashMap<>();
busDetails.put(config.TAG_ID, id);
busDetails.put(config.TAG_BUSNAME, busName);
busDetails.put(config.TAG_TERMINAL, terminal);
list.add(busDetails);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
SearchResultsActivity.this, list, R.layout.result_list_item, new String[] {
config.TAG_ID, config.TAG_BUSNAME, config.TAG_TERMINAL}, new int[] {R.id.id, R.id.busName,
R.id.terminal});
listView.setAdapter(adapter);
}
private void getJSON() {
class GetJSON extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(SearchResultsActivity.this, "Message", "Fetching data... Please wait.", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showBusList();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(config.URL_SEARCH, destination);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
RequestHandler.java
//handles requests
public String sendGetRequestParam(String requestURL, String id){
StringBuilder sb =new StringBuilder();
try {
URL url = new URL(requestURL+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while((s=bufferedReader.readLine())!=null){
sb.append(s+"\n");
}
}catch(Exception e){
}
return sb.toString();
}
PHP file
<?php
$connection = mysqli_connect("mysql.hostinger.ph", "u679871488_bus", "Damnyoufudge20", "u679871488_bus") or die("Error " . mysqli_error($connection));
$des = $_GET['destination'];
$sql = "SELECT * from appDB WHERE route LIKE '%".$des."%'";
$result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
$thisArray = array();
while($row = mysqli_fetch_assoc($result)) {
$thisArray[] = $row;
}
echo json_encode(array('busDetails' => $thisArray));
Error from logcat
03-06 16:10:25.525 31710-31710/com.thesis.iwander W/System.err: org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:159)
at org.json.JSONObject.<init>(JSONObject.java:172)
at com.thesis.iwander.SearchResultsActivity.showBusList(SearchResultsActivity.java:62)
at com.thesis.iwander.SearchResultsActivity.access$100(SearchResultsActivity.java:29)
at com.thesis.iwander.SearchResultsActivity$1GetJSON.onPostExecute(SearchResultsActivity.java:109)
at com.thesis.iwander.SearchResultsActivity$1GetJSON.onPostExecute(SearchResultsActivity.java:93)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
try array_push method in php in your php code
while($row = mysqli_fetch_assoc($result)) {
//$thisArray[] = $row;
array_push($thisArray, $row);
}
i think it'll work.
Try it once and check if get this data in android.
It is bad practice to append user input directly to sql query in php like you used '%".$des."%'. It causes SQL Injection Attacks.
Always prefer mysqli_prepare($sql) to avoid SQL Injection Attacks.
UPDATE 1
In SearchResultsActivity.java, try to replace
destination = a.getStringExtra("to");
this line with
destination = a.getExtras().getString("to");
Log.e("tag", " DESTINATION :: " + destination);
And check if you're getting the text from first activity.
UPDATE 2
Never ever forget to catch exceptions you're throwing.
You forgot to catch exception in sendGetRequestParam method. Catch it and print it. So you'll know if there is any error connecting to server.
I have a custom ListView layout that I got from a website. It allows me to click on an item from a list and repopulates the same layout with a new list of different items based on the item you clicked. The layout works fine and I got it to populate with information pulled from a database.
The problem that Im having is that instead of having it repopulate the layout with a new list when clicked, I would like it to go to another layout. I tried a couple things but had no luck. Here is my code. Thank you for the help in advance:
public class firstactivity extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
CustomAdapter adapter;
int pos=1;
public int picpos = 0;
LinkedList<String> region = new LinkedList<String>();
String name = null;
String something = null;
private Integer[] imgid = {
R.drawable.icon
};
RelativeLayout layr1;
Animation ar3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
String finaline = "";
//Get info from database
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http connection
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8888/PhpProject1/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag"," names: "+json_data.getString("name")
);
//Get an output to the screen
finaline = "\n\t" + jArray.getJSONObject(i);
something = finaline.substring(finaline.indexOf(',',10));
name = something.substring(9,finaline.indexOf('\"', 9));
region.add(something);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
//set list with information from database
for(int i=0;i<region.size();i++){
try {
rd = new RowData(i,region.get(i));
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
adapter = new CustomAdapter(this, R.layout.second_list,R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
//getListView().setOnItemClickListener(this);
}
/*private OnClickListener SaveListener = new OnClickListener(){
public void onClick(View v){
setContentView(R.layout.newlayout);
}
};*/
/*protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
setContentView(R.layout.newlayout);
//final Intent intent = new Intent();
//startActivityForResult(intent, position);
}*/
public void onListItemClick(ListView parent, View v, int position, long id) {
adapter = (CustomAdapter) parent.getAdapter();
data.removeAllElements();
//String insert_list;
////
//if(position==0) {
/*setContentView(R.layout.newlayout);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText((String)region.get(0));*/
//setListAdapter(adapter);
//getListView().setTextFilterEnabled(true);
if(position == 0)
setContentView(R.layout.newlayout);
}
private class RowData {
protected int mId;
protected String mTitle;
RowData(int id,String title){
mId=id;
mTitle = title;
}
#Override
public String toString() {
return mId+" "+mTitle;
}
}
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;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.second_list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
i11=holder.getImage();
i11.setImageResource(imgid[0]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
It sounds like what you are looking for is a way to go to a new Activity and display a new ListView. To go to a new Activity you would do something like:
startActivity(new Intent(this, SecondActivity.class));
This line of code is creating a new Intent object, which tells Android which Activity to open next. You are then passing that Intent to the startActivity method of your current Activity. A more detailed explanation is here: http://developer.android.com/reference/android/app/Activity.html#StartingActivities
It also might be useful for you to pass some information to the next Activity, like the name of a state which was selected. You can do that by putting this information into the Intent object:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("state", "New York");
startActivity(intent);
You can get this data from within SecondActivity by doing:
Intent incomingIntent = getIntent();
String state = incomingIntent.getExtras().getString("state");
SecondActivity refers to a new class which extends Activity that you will need to define in your code. Don't forget to add it to your manifest.xml too, otherwise you will get an exception when trying to start it.