Android looping through onlinedatabase - android

When i'm trying to loop through the database, my activity hang up and nothing happen.
final JSONArray jArray = new JSONArray(result);
while (i < jArray.length()) {
JSONObject json = jArray.getJSONObject(i);
title.setText(json.getString("PhoneName"));
price.setText("Price : " + json.getString("PhonePrice"));
modelnumber.setText(json.getString("ModelNumber"));
arrowfront.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
}
});
arrowback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
i--;
}
});
}
} catch (Exception e) {
Log.e("tag", e.toString());
}
}
i'm trying to connect to the database, at first the textviews display the firstitem, then when i click on arrow i want to display the second row of the table and so on.. But when the activity launch, it hangs up and nothing happens even that i don't receive error's in logcat
And in the logcat, "tag" doesn't appear. Any suggestion??

Ok, do it this way :
final JSONArray jArray = new JSONArray(result);
private ArrayList<HashMap<String,String>> resultList = new ArrayList<HashMap<String,String>>();
int position=0;
for (int i=0;i<jArray.length();i++) {
HashMap<String,String> hm= new HashMap<String,String>();
JSONObject json = jArray.getJSONObject(i);
hm.put("title",json.getString("PhoneName"));
hm.put("price","Price : " + json.getString("PhonePrice"));
hm.put("modelNumber",json.getString("ModelNumber"));
resultList.add(hm);
}
arrowfront.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
position++;
HashMap <String,String> frontHm = new HashMap <String,String>();
frontHm=resultList.get(position);
title.setText(frontHM.get("title");
price.setText(frontHM.get("price"));
modelnumber.setText(frontHM.get("modelNumber"));
}
});
arrowback.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
position--;
HashMap <String,String> backHm = new HashMap <String,String>();
backHm=resultList.get(position);
title.setText(backHM.get("title");
price.setText(backHM.get("price"));
modelnumber.setText(backHM.get("modelNumber"));
}
});
So idea is to keep tracking the position inside global "position" variable. Also I didn't add logic inside click listeners to check first and last position because you can not go out of bounds of arraylist, please do it yourself.

Related

ArrayList for show products not work secondly

i have two intent city and product.first app open city intent show and user select city . now city pass to product intent for show products.
I use array list for fetching data from php api and show to user in product intent:
ArrayList<HashMap<String,String>> getDatalist;
StringRequest stringRequest = new StringRequest(Request.Method.GET, jsonUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
obj = new JSONObject(response);
prdArray = obj.getJSONArray("prd");
for(int aind = 0 ; aind < 2; aind++) {
final JSONObject do_id = prdArray.getJSONObject(aind);
String email = do_id.getString("email");
String phone = do_id.getString("phone");
HashMap<String,String> map = new HashMap<>();
map.put("KEY_EMAIL",email);
map.put("KEY_PHONE",phone);
getDatalist.add(map);
Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_SHORT).show();
}
}catch (JSONException e) {
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
anything is OK now.Nut i have a bottom for change city when user click it . city Intent show and after city changed he coma back to product intent.but now products not show :(
Button cityChange=(Button)findViewById(R.id.cityChange);
cityChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cityChangeIntent = new Intent(home.this,city.class);
cityChangeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(cityChangeIntent);
finish();
}
});
Recycleviewadapter:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
if (holder instanceof ViewHolderRow) {
HashMap<String,String> map = mDataset.get(position);
ViewHolderRow userViewHolder = (ViewHolderRow) holder;
userViewHolder.txtEmail.setText(map.get("KEY_EMAIL"));
userViewHolder.txtPhone.setText(map.get("KEY_PHONE"));
.....
Use for loop like this
for(int aind = 0 ; aind < prdArray.size; aind++) {
//your code
}

Get listview data while checked and pass it to another activity

Ive been searching for the right answer but nothing can solve my problems. I have a list view which is populated by my database from webserver. So basically what need is to get the data from the listview that is checked by user and pass the data to another activity. Sorry for my bad english hope you guys can help me.
Error ive received
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at firin.myuploads.Attendance$1.onClick(Attendance.java:74)
Attendance.java
public class Attendance extends AppCompatActivity {
//For Checkbox
ArrayList<String> selectedItems=new ArrayList<>();
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private CheckBox cb;
private Button bGet;
//private id[] id;
private static String url = "www.myphpurl.com";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
contactList = new ArrayList<>();
bGet = (Button) findViewById(R.id.button7);
lv = (ListView) findViewById(R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
new GetContacts().execute();
bGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String selected =((TextView)view.findViewById(R.id.mobile)).getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
cb.setChecked(true);
int len = lv.getCount();
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = selectedItems.get(i);
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();
/*some code to save data in MainActivity*/
Intent in = new Intent(Attendance.this, SendMail.class);
in.putExtra("ListValue", item);
startActivity(in);}
}
});
}
This is the code where i populate my data to the listview
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray result = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String id = c.getString("userID");
String studentName = c.getString("studentName");
String parentName = c.getString("parentName");
String parentEmail = c.getString("parentEmail");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("UID", id);
contact.put("sName", studentName);
contact.put("pName", parentName);
contact.put("pEmail", parentEmail);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Attendance.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Attendance.this, contactList,
R.layout.list_item, new String[]{"sName", "pName",
"pEmail"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
Is this how i set my setOnClick?
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selected =((TextView)findViewById(R.id.mobile)).getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
cb.setChecked(true);
}});
Hope you guys can help me. thanks in advance
First you need to get how many item is selected in the listview, then after store in another array and pass that array to another activity.
Set you listview selection mode as Multi Choice.
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Set Listener on listview as below
ArrayList<String> selectedItem = new ArrayList();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
adapter.getView(position, view, parent).setBackgroundColor(getResources().getColor(R.color.btn_login));
adapter.notifyDataSetChanged();
Log.i(TAG, "Selected Item is " + stateList.get(position));
selectedItem.add(yourArray.get(position))
}
});
you can invok your intent and pass selectedItem to that intent like this
Intent intent = new Intent(activity, YourActivity.class);
intent.putStringArrayListExtra("selected_list", selectedItem);
startActivity(intent);
and In your receiving intent you need to do:
ArrayList<String> selectedItem;
Intent i = getIntent();
selectedItem = i.getStringArrayListExtra("selected_list");

When trying to add a listener to textview added programmatically only the last one works as intended

After a consumption of a webservice, i got an json object, after the parse i need to create a textview (for each element) and to each of them add a listener.
currently ALL TEXTVIEW get binded with the same ID (the last one) so they all pass the same extra (in this case id_asignacion)
Here the code that adds the textviews and binds them with a listener:
for (int i=0; i < jArray.length(); i++){
try {
JSONObject oneObject = jArray.getJSONObject(i);
descripcion = oneObject.getString("descripcion");
direccion = oneObject.getString("direccion");
id_denuncia = oneObject.getString("idDenuncia");
TextView nueva_asignacion = new TextView(ctx);
ImageView separador = new ImageView(ctx);
separador.setImageResource(R.drawable.barrablanca);
nueva_asignacion.setTextColor(getResources().getColor(R.color.gris_claro));
nueva_asignacion.setTextSize(getResources().getDimension(R.dimen.dpde10));
if(int_color == 0){
nueva_asignacion.setBackgroundColor(getResources().getColor(R.color.blanco));
int_color = 1;
}else{
nueva_asignacion.setBackgroundColor(getResources().getColor(R.color.gris_perfil));
int_color = 0;
}
nueva_asignacion.setText(descripcion + ".\nEn: " + direccion);
linearLayout_asignaciones.addView(nueva_asignacion);
nueva_asignacion.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
abrir_detalle_asignacion(id_denuncia);
}
});
linearLayout_asignaciones.addView(separador);
} catch (JSONException e) {
e.printStackTrace();
}
}
The function that i bind them to (abrir_detalle_asignacion ) its the following:
public void abrir_detalle_asignacion(String id_denuncia) {
Intent intent = new Intent(ctx, DetalleAsignacion.class);
intent.putExtra("RUT", RutLog);
intent.putExtra("id_inspector", id_inspector);
intent.putExtra("id_asignacion", id_denuncia);
startActivityForResult(intent, 0);
overridePendingTransition(R.anim.from_middle, R.anim.to_middle);
}
TL DR: Every Textview is Binded with the SAME id_denuncia, So all the Textviews do the same thing.
I think you have a problem with id_denuncia , because you override it's value on every iteration and the last value is actually passed on every click, and that's why only the last TextView works as expected
There are several solutions, for example
pass the string from the json by index, something like -
abrir_detalle_asignacion(jArray.getJSONObject(i).getString("idDenuncia"));
OR
Maybe store the values in an array, and pass the value from the array by index to the method:
abrir_detalle_asignacion(id_denuncia_array[i]);
You can declare own class
class MyOnClick implements View.OnClickListener {
private final String id;
MyOnClick(String s) {
id = new String(s);
}
public void onClick(View v) {
abrir_detalle_asignacion(id);
}
}
and use it: nueva_asignacion.setOnClickListener(new MyOnClick(id_denuncia))

Text field doesn't change in gallery android

I have gridview which load few images thumbnails. When I click on some image is opened in new activity full image. Now I trying to add some description about the image. When activity is loaded the info for this image is loaded also. So far so good..
The problem comes when I click on button next which load next image(full image without to back on the gridview with thumbnails) the description doesn't update and change for the next image. Is just same description for every image.
Here I download thumb, full_image and description,
String url = "http://myhost/get.php?id=" + my_id;
JSONArray data;
try {
resultServer = getJSONUrl(url);
data = new JSONArray(resultServer);
MyArrList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
map.put("id", (String)c.getString("id"));
map.put("description", (String)c.getString("description"));
// Thumbnail Get ImageBitmap To Bitmap
map.put("ImagePathThum", (String)c.getString("image"));
map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("image")));
// Full (for View Full)
map.put("ImagePathFull", (String)c.getString("image_big"));
MyArrList.add(map);
}
Then this is the gridView() which display thumbs
public void ShowAllContent()
{
// gridView1
final GridView gridV = (GridView)findViewById(R.id.gridView1);
gridV.setAdapter(new ImageAdapter(act1.this,MyArrList));
// OnClick
gridV.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
String Position = String.valueOf(position);
Intent newActivity = new Intent(act1.this,act2.class);
newActivity.putExtra("Position", Position);
newActivity.putExtra("resultServer", resultServer);
newActivity.putExtra("description", MyArrList.get(position).get("description").toString());
startActivity(newActivity);
finish();
}
});
}
Then In act2
TextView txtView;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
txtView = (TextView) findViewById(R.id.text);
Intent intent= getIntent();
curPosition = Integer.parseInt(intent.getStringExtra("Position"));
resultServer = String.valueOf(intent.getStringExtra("resultServer"));
textDescription = getIntent().getStringExtra("description");
((TextView)findViewById(R.id.text)).setText(textDescription+"");
try {
MyArrList = ConvertJSONtoArrayList(resultServer);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("ArrayList Size",String.valueOf(MyArrList.size()));
// Show Image Full
new DownloadFullPhotoFileAsync().execute();
// Button Back
back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
curPosition = curPosition - 1;
new DownloadFullPhotoFileAsync().execute();
}
});
// Button Next
next = (Button) findViewById(R.id.btnNext);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
curPosition = curPosition + 1;
new DownloadFullPhotoFileAsync().execute();
}
});
}
// Show Image Full
public void ShowImageFull(String imageName, Bitmap imgFull)
{
// Prepare Button (Back)
if(curPosition <= 0)
{
back.setEnabled(false);
}
else
{
back.setEnabled(true);
}
// Prepare Button (Next)
Log.d("curPosition",String.valueOf(curPosition));
Log.d("MyArrList.size",String.valueOf(MyArrList.size()));
if(curPosition >= MyArrList.size() - 1)
{
next.setEnabled(false);
}
else
{
next.setEnabled(true);
}
ImageView image = (ImageView) findViewById(R.id.fullimage);
try
{
image.setImageBitmap(imgFull);
} catch (Exception e) {
// When Error
image.setImageResource(android.R.drawable.ic_menu_report_image);
}
// Show Toast
Toast.makeText(act2.this,imageName,Toast.LENGTH_LONG).show();
}
public ArrayList<HashMap<String, Object>> ConvertJSONtoArrayList(String json) throws JSONException
{
JSONArray data = new JSONArray(resultServer);
ArrayList<HashMap<String, Object>> arr = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
map.put("ImageName", (String)c.getString("name"));
map.put("ImagePathThum", (String)c.getString("image"));
map.put("ImagePathFull", (String)c.getString("image_big"));
map.put("description", (String)c.getString("description"));
arr.add(map);
}
return arr;
}
}
public class DownloadFullPhotoFileAsync extends AsyncTask<String, Void, Void> {
String strImageName = "";
String ImageFullPhoto = "";
Bitmap ImageFullBitmap = null;
#Override
protected Void doInBackground(String... params) {
strImageName = MyArrList.get(curPosition).get("ImageName").toString();
ImageFullPhoto = MyArrList.get(curPosition).get("ImagePathFull").toString();
ImageFullBitmap = (Bitmap)loadBitmap(ImageFullPhoto);
return null;
}
}
I'm sorry for long source code but I don't know which part exactly is needed.
I've tried to add in DownloadFullPhotoFileAsync
textDescription = MyArrList.get(curPosition).get("description").toString();
so when is loaded new DownloadFullPhotoFileAsync().execute(); in button next to load also this but I guess this is wrong since it doesn't work.
You can't setText in DoInBackground() function in Async Task, but you can do a setText of your description on PostExecute() which is a function of AsyncTask.
So i think you should try to set your description in PostExecute function in your Asynctask.
take a look at : http://developer.android.com/reference/android/os/AsyncTask.html
I hope this help,
Cheers !

Parsing multiple json object value leading in last value of that object.

i am working on an app, where i am getting response(Json) from my remote server.I am also able to parse and place markers based on that response.But i am failing in parsing ph data from response and passing it into another activity.
It is sending only phone number of last json object data in setOnInfoWindowClickListener event.
I know some minor modifications i have to made. Please suggest me in this.
This is the Json response i am getting.
[
{
id: 965,
distance: "1.47",
ph: "33441111",
name: "XYZ",
LS: " abcdef",
point: "77.588018,12.959282"
},
{
id: 965,
distance: "1.47",
ph: "33441111",
name: "XYZ",
LS: " abcdef",
point: "77.588018,12.959282"
},
.
.
]
I tried this way to parse
private class HttpGetTask extends AsyncTask<Void, Void, String> {
// Showing progress dialog
// Passing URL
#Override
protected String doInBackground(Void... params) {
// http stuff
}
#Override
protected void onPostExecute(String result) {
if (pDialog.isShowing())
pDialog.dismiss();
try {
JSONArray json = new JSONArray(result);
for (int i = 0; i < json.length(); i++) {
Log.v("Response", result);
final JSONObject e = json.getJSONObject(i);
String point = e.getString("point");
final String phone = e.getString("ph");
String[] point2 = point.split(",");
double lat1 = Double.parseDouble(point2[0]);
double lng1 = Double.parseDouble(point2[1]);
gMap.addMarker(new MarkerOptions()
.title(e.getString("name"))
.snippet(
e.getString("LS") + "*" + e.getString("ph"))
.position(new LatLng(lng1, lat1))
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pmr)));
gMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoContents(Marker mrkr) {
// TODO Auto-generated method stub
String name = mrkr.getTitle();
String detail = mrkr.getSnippet();
String trimmedDetail = detail.substring(0, 60);
Log.v("Info", name + " " + detail);
View v = getLayoutInflater().inflate(
R.layout.infowindow, null);
TextView title = (TextView) v
.findViewById(R.id.titleTV);
TextView snippet = (TextView) v
.findViewById(R.id.snippetTV);
title.setText("" + name);
snippet.setText("" + trimmedDetail);
return v;
}
});
gMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent myIntent = new Intent(getBaseContext(),
DtActivity.class);
myIntent.putExtra("title", arg0.getTitle());
myIntent.putExtra("detail", arg0.getSnippet());
myIntent.putExtra("ph1", phone);
// How to access and send ph here.
try {
String ph = e.getString("ph");
myIntent.putExtra("ph", ph);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(myIntent);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
You need to Initialize the gMap Globaly and add the marker inside the for Loop. Remove the adapter and infowindow click listener codes from form loop and paste it outside. Kindly check the below sample.
public class Example extends FragmentActivity implements OnInfoWindowClickListener {
public static GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setOnInfoWindowClickListener(this);
// Inside the Loop
mMap.addMarker(new MarkerOptions().title(e.getString("name"))
.snippet(e.getString("LS") + "*" + e.getString("ph"))
.position(new LatLng(lng1, lat1))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pmr)));
// Close the loop
}
#Override
public void onInfoWindowClick(Marker marker) {
// here you can get title, snippet, lat,lng of selected marker. then you
// can start activity.
}
}
Kindly paste the for loop inside the onPostExecute of your Asyntask Class.
Add this code snippet to get the phone number.I have marked it with you will get your phone number here
gMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
///////////////you will get your phone number here////////////////////////
for (int j = 0; j < json.length(); j++) {
JSONObject jo = json.getJSONObject(j);
if(arg0.getTitle().equals(jo.getString("title"))){
String phone= jo.getString("ph");
}
///////////////you will get your phone number here////////////////////////
Intent myIntent = new Intent(getBaseContext(),
DtActivity.class);
myIntent.putExtra("title", arg0.getTitle());
myIntent.putExtra("detail", arg0.getSnippet());
myIntent.putExtra("ph1", phone);
startActivity(myIntent);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem is that you are setting a new setInfoWindowAdapter and setOnInfoWindowClickListener
each time you iterate to ur for loop and the last iterate or the last json object will be the InfoWindowAdapter and InfoWindowClickListener that why you are getting the last json, you can only set it once not multiple times except for the add marker.
Dont put the setInfoWindowAdapter and setOnInfoWindowClickListener in the for loop

Categories

Resources