I'm trying to pass an ArrayList filled in the getPartidos() method with volley to another activity through the btnClick_Normal(View v) method, but whenever I press any button the uses the method I get an error saying miListaPartidos is empty (this).
The URL is online and working properly. Why could this be happening and how much of the code is wrong?
This is my Activity
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Act1_1 extends AppCompatActivity {
public String urlPartidos="https://.."; /*hid the url, it's working properly*/
public ArrayList<Partido> miListaPartidos=new ArrayList<>();
public Button btns1;
public Button btns2;
public Button btns3;
public Button btns4;
public Button btns5;
public Button btns6;
public Button btns7;
public Button btns8;
public Button btnE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act1_1);
btns1=findViewById(R.id.btns1);
btns2=findViewById(R.id.btns2);
btns3=findViewById(R.id.btns3);
btns4=findViewById(R.id.btns4);
btns5=findViewById(R.id.btns5);
btns6=findViewById(R.id.btns6);
btns7=findViewById(R.id.btns7);
btns8=findViewById(R.id.btns8);
btnE=findViewById(R.id.btnE);
getPartidos();
}
public void btnClick_Normal(View v){
Intent intent=new Intent(getApplicationContext(),Act1_1_1.class);
int id1=(Integer.parseInt((String)v.getTag()));
ArrayList<Partido> listaEq=new ArrayList<>();
for(int i=(((id1-1)*6)); i<=(id1*6)-1;i++ ) {
listaEq.add(miListaPartidos.get(i));
}
intent.putExtra("listaEq", listaEq);
startActivity(intent);
}
public void btnClick_Especial(View v){
Intent intent=new Intent(getApplicationContext(),Act1_1_2.class);
ArrayList<Partido> listaEq=new ArrayList<>();
for(int i=48; i<=63;i++ ) {
listaEq.add(miListaPartidos.get(i));
}
intent.putExtra("listaEq2", listaEq);
startActivity(intent);
}
public void getPartidos(){
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonObjectRequest jSonObjectRequest=new JsonObjectRequest(Request.Method.GET,urlPartidos, null, new Response.Listener<JSONObject>(){
public void onResponse(JSONObject response){
try{
JSONArray jsonArrayPartidos=response.getJSONArray("results");
if(jsonArrayPartidos.length()>0) {
for (int i = 0; i < jsonArrayPartidos.length(); i++) {
JSONObject jsonPartido = jsonArrayPartidos.getJSONObject(i);
final int id = jsonPartido.getInt("id");
final String detalles = jsonPartido.getString("details");
final String equipo1 = jsonPartido.getString("team1");
final String equipo2 = jsonPartido.getString("team2");
final int goles1 = jsonPartido.getInt("goals1");
final int goles2 = jsonPartido.getInt("goals2");
final Partido nuevoPartido = new Partido(id, detalles, equipo1, equipo2, goles1, goles2);
miListaPartidos.add(nuevoPartido);
}
}
}
catch(JSONException je){ }
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jSonObjectRequest);
}
}
And this is my Partido class
public class Partido {
private int id;
private String detalles;
private String equipo1;
private String equipo2;
private int goles1;
private int goles2;
public Partido(int id, String detalles, String equipo1, String equipo2, int goles1, int goles2){
this.id=id;
this.detalles=detalles;
this.equipo1=equipo1;
this.equipo2=equipo2;
this.goles1=goles1;
this.goles2=goles2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDetalles() {
return detalles;
}
public void setDetalles(String detalles) {
this.detalles = detalles;
}
public String getEquipo1() {
return equipo1;
}
public void setEquipo1(String equipo1) {
this.equipo1 = equipo1;
}
public String getEquipo2() {
return equipo2;
}
public void setEquipo2(String equipo2) {
this.equipo2 = equipo2;
}
public int getGoles1() {
return goles1;
}
public void setGoles1(int goles1) {
this.goles1 = goles1;
}
public int getGoles2() {
return goles2;
}
public void setGoles2(int goles2) {
this.goles2 = goles2;
}
}
If your list is empty, then there may be a problem with the Json itself. Some times they have some extra characters, So
try to validate the your Json using JsonLint or Code beautify
In your catch Json exception block, try to print the stack trace and grab the message
catch(JSONException je){
je.printStackTrace();
Log.d("ERR",je.getMessage()) ;
}
Please implement Serializable in Partido class
public class Partido implements Serializable {
private int id;
private String detalles;
private String equipo1;
private String equipo2;
private int goles1;
private int goles2;
public Partido(int id, String detalles, String equipo1, String equipo2, int goles1, int goles2){
this.id=id;
this.detalles=detalles;
this.equipo1=equipo1;
this.equipo2=equipo2;
this.goles1=goles1;
this.goles2=goles2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDetalles() {
return detalles;
}
public void setDetalles(String detalles) {
this.detalles = detalles;
}
public String getEquipo1() {
return equipo1;
}
public void setEquipo1(String equipo1) {
this.equipo1 = equipo1;
}
public String getEquipo2() {
return equipo2;
}
public void setEquipo2(String equipo2) {
this.equipo2 = equipo2;
}
public int getGoles1() {
return goles1;
}
public void setGoles1(int goles1) {
this.goles1 = goles1;
}
public int getGoles2() {
return goles2;
}
public void setGoles2(int goles2) {
this.goles2 = goles2;
}
}
This is code to receive data in Act1_1_2
misPartidos = (ArrayList<Partido>) getIntent().getSerializableExtra("listaEq2");
Hope this will be help you!
Related
I have a object class that I want to use it between activities.
I used exactly the same method for another activities and worked perfectly fine. But here I can't figure it out what I am doing wrong. This is the object class :
`package com.mecachrome.ffbf;
import android.os.Parcel;
import android.os.Parcelable;
public class topic implements Parcelable {
public static Creator<topic> getCREATOR() {
return CREATOR;
}
public static final Creator<topic> CREATOR = new Creator<topic>() {
#Override
public topic createFromParcel(Parcel in) {
return new topic(in);
}
#Override
public topic [] newArray(int size) {
return new topic[size];
}
};
private String name;
private String comment;
private String id;
private String username;
public topic() {
}
public topic(String name, String comment, String id, String username) {
this.name = name;
this.comment = comment;
this.id = id;
this.username = username;
}
protected topic(Parcel in) {
name = in.readString();
comment = in.readString();
id = in.readString();
username = in.readString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public String toString() {
return "topic{" +
"name='" + name + '\'' +
", comment='" + comment + '\'' +
", id='" + id + '\'' +
", username='" + username + '\'' +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(comment);
dest.writeString(id);
dest.writeString(username);
}
}`
This is the class that I want to take the object from:
`package com.mecachrome.ffbf;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class forum extends AppCompatActivity {
RecyclerView rv_forum;
forumAdapter myadapter;
Button add_topic;
Button test;
DatabaseReference databaseref;
private ArrayList<topic> topicList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum);
add_topic = findViewById(R.id.btn_new_topic);
rv_forum = findViewById(R.id.rv_topics);
rv_forum.setHasFixedSize(true);
rv_forum.setLayoutManager(new LinearLayoutManager(this));
test = findViewById(R.id.test_btn);
topicList = new ArrayList<>();
databaseref = FirebaseDatabase.getInstance().getReference("forum_topics");
databaseref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dss: snapshot.getChildren()){
topic top = dss.getValue(topic.class);
topicList.add(top);
}
myadapter = new forumAdapter(forum.this, topicList, mTopic -> {
Intent intent = new Intent(forum.this, topic_chat.class);
intent.putExtra("topic",mTopic);
startActivity(intent);
});
rv_forum.setAdapter(myadapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(forum.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
add_topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(forum.this, add_new_topic.class);
startActivity(i);
}
});
}
}`
And this is the class that I want to transfer the object to:
`package com.mecachrome.ffbf;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class topic_chat extends AppCompatActivity {
RecyclerView rv_chat;
chatAdapter myadapter;
Button send;
TextView topic_name;
TextView chat_text;
String chat;
private topic mTopic;
private ArrayList<chat> chatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic_chat);
mTopic = getIntent().getParcelableExtra("topic");
send = findViewById(R.id.btn_send_chat);
rv_chat = findViewById(R.id.rv_topics);
rv_chat.setHasFixedSize(true);
rv_chat.setLayoutManager(new LinearLayoutManager(this));
topic_name = findViewById(R.id.tv_topic_name);
chat_text = findViewById(R.id.et_comment);
chat = chat_text.getText().toString().trim();
chatList = new ArrayList<>();
DatabaseReference databaseref = FirebaseDatabase.getInstance().getReference("forum_topics").child(mTopic.getId()).child("chat");
topic_name.setText(mTopic.getName());
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance(DateFormat.SHORT).format(calendar.getTime());
chatList = new ArrayList<>();
databaseref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dss: snapshot.getChildren()){
chat mess = dss.getValue(chat.class);
chatList.add(mess);
}
myadapter = new chatAdapter(topic_chat.this, chatList, chat -> {
Intent intent = new Intent(topic_chat.this, topic_chat.class);
startActivity(intent);
});
rv_chat.setAdapter(myadapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(topic_chat.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chat msg = new chat(mTopic.getName(),chat,mTopic.getId(),currentDate);
databaseref.setValue(msg).addOnCompleteListener(task1 -> {
if (task1.isSuccessful()){
Toast.makeText(topic_chat.this, "Review was been added Successfully", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(topic_chat.this, "Review failed to post. Try Again!", Toast.LENGTH_SHORT).show();
}
});;
}
});
}
}`
The object class is "topic"
The error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mecachrome.ffbf.topic.getId()' on a null object reference
On this line
DatabaseReference databaseref = FirebaseDatabase.getInstance().getReference("forum_topics").child(mTopic.getId()).child("chat");
because mTopic.getId() is null. Any help?
public class Constant {
public static final String FIREBASE_CHAT_URL="https://roadcaremap.firebaseio.com/";
public static final String CHILD_USERS="users";
public static final String CHILD_CHAT="chat";
public static final String KEY_SEND_USER="key_send_user";
public static final String CHILD_CONNECTION="connecttion";
public static final String CHILD_LATITUDE="latitude";
public static final String CHILD_LONGITUDE="longitude";
public static final String KEY_EMAIL="email";
public static final String KEY_ONLINE="online";
public static final String KEY_OFFLINE="offline";
public static final String KEY_CLOSE="key_close";
}
I'm new to android. Recently, I encountered a problem when running the application on my device. The app crashes and shows me an error on this line which I do not know how to solve. I've added the code and picture of the logcat. Any help would be much appreciated. The error is shown in this line.
rootUrl = new Firebase(Constant.FIREBASE_CHAT_URL);
package com.snapsofts.demogmap.activity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.firebase.client.AuthData;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.gson.Gson;
import com.snapsofts.demogmap.R;
import com.snapsofts.demogmap.Services.LocationService;
import com.snapsofts.demogmap.common.Constant;
import com.snapsofts.demogmap.object.User;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
private Firebase rootUrl;
private Firebase urlCurrenUser;
private Firebase urlAllUser;
private FirebaseAuth mAuth;
private Firebase.AuthStateListener mAuthStateListener;
private String currenUserId;
private String currenUserEmail;
private ArrayList<User> arrUser;
private AllUserAdapter allUserAdapter;
private ArrayList<String> arrStringEmail;
private ValueEventListener valueEventListenerUserConnected;
private User currenUser;
#BindView(R.id.btnLogout)
Button btnLogout;
#BindView(R.id.lvUser)
ListView lvUser;
#BindView(R.id.tvUsserName)
TextView tvUsserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
MainActivity.this.startService(new Intent(MainActivity.this, LocationService.class));
arrStringEmail = new ArrayList<>();
arrUser = new ArrayList<User>();
allUserAdapter = new AllUserAdapter(MainActivity.this, 0, arrUser);
lvUser.setAdapter(allUserAdapter);
lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(MainActivity.this,MapsActivity.class);
User user=arrUser.get(position);
Gson gson=new Gson();
intent.putExtra(Constant.KEY_SEND_USER,gson.toJson(user).toString()+"---"+gson.toJson(currenUser).toString());
startActivity(intent);
mAuth = FirebaseAuth.getInstance();
}
});
rootUrl = new Firebase(Constant.FIREBASE_CHAT_URL);
mAuthStateListener = new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
setAuthenticatedUser();
}
};
rootUrl.addAuthStateListener(mAuthStateListener);
}
private void setAuthenticatedUser () {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
currenUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
currenUserEmail = FirebaseAuth.getInstance().getCurrentUser().getEmail();
getCurrenUser();
getAllUser();
} else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
public void getCurrenUser() {
urlCurrenUser = new Firebase(Constant.FIREBASE_CHAT_URL).child(Constant.CHILD_USERS).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
urlCurrenUser.addValueEventListener(valueEventListenerCurrenUser);
valueEventListenerUserConnected=rootUrl.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean connected = (Boolean) dataSnapshot.getValue();
if (connected) {
urlCurrenUser.child(Constant.CHILD_CONNECTION).setValue(Constant.KEY_ONLINE);
urlCurrenUser.child(Constant.CHILD_CONNECTION).onDisconnect().setValue(Constant.KEY_OFFLINE);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
private ValueEventListener valueEventListenerCurrenUser = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
tvUsserName.setText("Hello "+user.name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
public void getAllUser() {
urlAllUser = new Firebase(Constant.FIREBASE_CHAT_URL).child(Constant.CHILD_USERS);
urlAllUser.addChildEventListener(childEventListenerAllUser);
}
private ChildEventListener childEventListenerAllUser = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
if (!dataSnapshot.getKey().equals(currenUserId)){
arrStringEmail.add(user.email);
arrUser.add(user);
allUserAdapter.notifyDataSetChanged();
}else {
currenUser=user;
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
if (!dataSnapshot.getKey().equals(currenUserId)){
User user = dataSnapshot.getValue(User.class);
int index = arrStringEmail.indexOf(user.email);
arrUser.set(index, user);
allUserAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
#Override
protected void onDestroy() {
super.onDestroy();
try {
rootUrl.removeAuthStateListener(mAuthStateListener);
} catch (Exception e) {
}
try {
urlCurrenUser.removeEventListener(valueEventListenerCurrenUser);
} catch (Exception e) {
}
try {
urlAllUser.removeEventListener(childEventListenerAllUser);
} catch (Exception e) {
}
try {
rootUrl.getRoot().child(".info/connected").removeEventListener(valueEventListenerUserConnected);
}catch (Exception e){}
}
#OnClick(R.id.btnLogout)
public void btnLogout() {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
stopService(new Intent(this, LocationService.class));
AuthUI.getInstance().signOut(this);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
}
public class AllUserAdapter extends ArrayAdapter<User> {
private Activity mActivity;
private ArrayList<User> mArrUser;
#BindView(R.id.tvNameUser)
TextView tvNameUser;
#BindView(R.id.tvStatus)
TextView tvStatus;
public AllUserAdapter(Activity mActivity, int resource, ArrayList<User> mArrUser) {
super(mActivity, resource, mArrUser);
this.mActivity = mActivity;
this.mArrUser = mArrUser;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = mActivity.getLayoutInflater();
convertView = layoutInflater.inflate(R.layout.item_list_user, null);
}
ButterKnife.bind(this, convertView);
tvNameUser.setText(mArrUser.get(position).name);
tvStatus.setText(mArrUser.get(position).connecttion);
if (mArrUser.get(position).connecttion.equals(Constant.KEY_ONLINE)){
tvStatus.setTextColor(Color.parseColor("#00FF00"));
}else {
tvStatus.setTextColor(Color.parseColor("#FF0000"));
}
return convertView;
}
}
}
logcat
I want to receive the value of the variable Id from the listItem clicked and to pass it in the other activity.But I am not receiving anything in the variable.
Here is the attached code :
MainActivity.java
package com.example.hp.citysearchapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<City> cityList = new ArrayList<City>();
private ListView listView;
private static String url;
ImageView searchIcon;
String idGet;
String edittextSearch;
TextInputLayout searchLayout;
EditText search;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.city_listView);
searchLayout=(TextInputLayout)findViewById(R.id.input_layout_search);
search=(EditText)findViewById(R.id.input_search);
searchIcon=(ImageView)findViewById(R.id.imageView);
adapter = new CustomListAdapter(this,cityList);
searchIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edittextSearch=search.getText().toString();
Log.d("hello2", search.getText().toString());
adapter.notifyDataSetChanged();
url = "http://test.maheshwari.org/services/testwebservice.asmx/SuggestCity?tryValue="+edittextSearch;
parsingMethod();
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,CityDetailsActivity.class);
City city = cityList.get(position);
idGet=city.getId();
Log.d("dfjdkfj", idGet); //Not receiving anything ,here is the problem
intent.putExtra("gettingId",idGet);
startActivity(intent);
}
});
}
private void parsingMethod() {
Log.d("hello", url);
pDialog = new ProgressDialog(this);
// Showing progress dialog
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest cityReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
// Parsing json
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
City city = new City();
try {
city.setId(obj.getString("Id"));
city.setTitle(obj.getString("Title"));
city.setDescription(obj.getString("Description"));
city.setExv1(obj.getString("ExtraValue1"));
Log.d("hello",obj.getString("ExtraValue1"));
city.setExv2(obj.getString("ExtraValue2"));
city.setExv3(obj.getString("ExtraValue3"));
city.setExv4(obj.getString("ExtraValue4"));
city.setExv5(obj.getString("ExtraValue5"));
city.setExv6(obj.getString("ExtraValue6"));
city.setExv7(obj.getString("ExtraValue7"));
city.setExv8(obj.getString("ExtraValue8"));
city.setExv9(obj.getString("ExtraValue9"));
cityList.add(city);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error){
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(cityReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
City.java
package com.example.hp.citysearchapp;
/**
* Created by hp on 22-03-2016.
*/
public class City {
String title,description,exv1,exv3,exv6,id,exv2,exv4,exv5,exv9,exv7,exv8;
public City(String title, String description, String id, String exv1, String exv3, String exv6,
String exv2, String exv4 , String exv5 , String exv7 , String exv8 , String exv9) {
this.title = title;
this.description=description;
this.id=id;
this.exv1=exv1;
this.exv2=exv2;
this.exv3=exv3;
this.exv4=exv4;
this.exv5=exv5;
this.exv6=exv6;
this.exv7=exv7;
this.exv8=exv8;
this.exv9=exv9;
}
public City() {
}
public String getId() {
return id;
}
public String getExv2() {
return exv2;
}
public String getExv4() {
return exv4;
}
public String getExv5() {
return exv5;
}
public String getExv7() {
return exv7;
}
public String getExv8() {
return exv8;
}
public String getExv9() {
return exv9;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getExv1() {
return exv1;
}
public String getExv3() {
return exv3;
}
public String getExv6() {
return exv6;
}
public void setId(String id) {
this.id = id;
}
public void setExv2(String exv2) {
this.exv2 = exv2;
}
public void setExv4(String exv4) {
this.exv4 = exv4;
}
public void setExv5(String exv5) {
this.exv5 = exv5;
}
public void setExv7(String exv7) {
this.exv7 = exv7;
}
public void setExv8(String exv8) {
this.exv8 = exv8;
}
public void setExv9(String exv9) {
this.exv9 = exv9;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setExv1(String exv1) {
this.exv1 = exv1;
}
public void setExv3(String exv3) {
this.exv3 = exv3;
}
public void setExv6(String exv6) {
this.exv6 = exv6;
}
}
Please modify your code a bit to achieve this --
You already have --
City city = cityList.get(position);
Now add this line to get Id from the ListItem clicked --
String Id = city.getExv3(); //Use one of your actual Getter methods accordingly.
Hope this helps!
Since I'm using a CustomAdapter for my list , I have to use the following code :
TextView textView = (TextView)view.findViewById(R.id.id); /*(R.id.id) is the id of the textview */
String gettingID=textView.getText().toString();
I need to pass an arraylist which contains object with a string and arraylist. I am unable to pass the arraylist to other activity. In the Activity1 the list contains value that I have verified.
DepositBn:
package support;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class DepositBn implements Parcelable {
private String limit;
#SerializedName("period")
private ArrayList<Rate> rateList;
protected DepositBn(Parcel in) {
limit = in.readString();
}
public String getLimit() {
return limit;
}
public void setLimit(String limit) {
this.limit = limit;
}
public ArrayList<Rate> getRateList() {
return rateList;
}
public void setRateList(ArrayList<Rate> rateList) {
this.rateList = rateList;
}
public class Rate {
private String rate;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(limit);
}
public static final Creator<DepositBn> CREATOR = new Creator<DepositBn>() {
#Override
public DepositBn createFromParcel(Parcel in) {
return new DepositBn(in);
}
#Override
public DepositBn[] newArray(int size) {
return new DepositBn[size];
}
};
}
In the Activity1:
#Override
protected void onPostExecute(ArrayList<DepositBn> result) {
super.onPostExecute(result);
System.out.println("result = " + result);
for (DepositBn depositBn : result) {
System.out.println("----" + depositBn.getLimit());
}
try {
Intent intent = new Intent(DepositRates.this, GenericRateDisplay.class);
Resources res = DepositRates.this.getResources();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("depositBnArrayList",result);
bundle.putString("pageName", res.getString(R.string.domesticRates));
intent.putExtras(bundle);
startActivity(intent);
} catch (Exception ex) {
ex.printStackTrace();
}
}
In Activity2:
package in.co.sbm.sbmvirtual;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import support.DepositBn;
public class GenericRateDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generic_rate_display);
Bundle b = this.getIntent().getExtras();
ArrayList<DepositBn> depositBnArrayList = b.getParcelableArrayList("depositBnArrayList");
//String pageName = b.getString("pageName");
ArrayList<String> rateList = new ArrayList();
for (DepositBn depositBn : depositBnArrayList) {
for(DepositBn.Rate rate : depositBn.getRateList()){
rateList.add(rate.toString());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(GenericRateDisplay.this,
android.R.layout.simple_list_item_1, rateList);
ListView listView = (ListView) findViewById(R.id.genericListView);
listView.setAdapter(adapter);
}
}
I have fixed it. I have used inner class as well which I did not serialize hence I was unable to use putSerializable. I have serialized both the outer and inner class and used intent.putSerializable.
I am using kinvey as my backend where I have a collection and would like to fetch data using appData.get. I have tried using the code below but it doesnt work. Could someone please tell me whats wrong with it.
package com.example.kinvey;
import com.kinvey.android.AsyncAppData;
import com.kinvey.android.callback.KinveyListCallback;
import com.kinvey.java.core.KinveyClientCallback;
import android.app.Activity;
import android.content.Entity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class ActionData extends Activity{
//protected static final String TAG = "LOG:";
public static final String TAG = "ActionData";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
public void onLoadClick(View view) {
AsyncAppData<Entity> myevents = MainActivity.mKinveyClient.appData("events",Entity.class);
myevents.get(new KinveyListCallback<Entity>() {
#Override
public void onSuccess(Entity[] result) {
Log.v(TAG, "received "+ result.length + " events");
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to fetch all", error);
}
});
}
And this is my Entity class.
package com.example.kinvey;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import com.kinvey.java.model.KinveyMetaData;
public class Entity extends GenericJson{
#Key("_id")
private String id;
#Key("_class")
private String _class;
#Key("author")
private String author;
#Key("relatedObj")
private String relatedObj;
#Key("relatedObjName")
private String relatedObjName;
#Key("type")
private String type;
#Key("_kmd")
private KinveyMetaData meta;
#Key("_acl")
private KinveyMetaData.AccessControlList acl;
public Entity(){}
public String getActionId() {
return id;
}
public void setActionId(String id) {
this.id = id;
}
public String getclass() {
return _class;
}
public void setclass(String _class) {
this._class = _class;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getRelatedObj() {
return relatedObj;
}
public void setRelatedObj(String relatedObj) {
this.relatedObj = relatedObj;
}
public String getRelatedObjName() {
return relatedObjName;
}
public void setRelatedObjName(String relatedObjName) {
this.relatedObjName = relatedObjName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}