I have a class which implements serializable and I am trying to send it's object using intent , so I am getting null object when I set that object using putExtra();
Below is my code.
YelpSearch.java(fromClass)
import android.app.ListActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class YelpSearch extends ListActivity implements Serializable {
#SuppressWarnings("serial")
class Business implements Serializable {
final String name;
final String url;
final String id;
public Business(String name, String url, String id) {
this.name = name;
this.url = url;
this.id = id;
}
#Override
public String toString() {
return name;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setTitle("Finding Tacos...");
setProgressBarIndeterminateVisibility(true);
Log.v("TAG","YelpSearchOnCreate");
new AsyncTask<Void, Void, List<Business>>() {
#Override
protected List<Business> doInBackground(Void... params) {
Log.v("TAG","Async List");
String businesses = Yelp.getYelp(YelpSearch.this).search("food", "91754");
Log.v("TAG","String businsesses"+businesses);
try {
Log.v("TAG","try");
return processJson(businesses);
} catch (JSONException e) {
return Collections.<Business>emptyList();
}
}
#Override
protected void onPostExecute(List<Business> businesses) {
Log.v("TAG","onPostExecute");
Log.v("BusinessesList","Businesses "+ businesses);
//setTitle("Tacos Found");
setProgressBarIndeterminateVisibility(false);
getListView().setAdapter(new ArrayAdapter<Business>(YelpSearch.this, android.R.layout.simple_list_item_1, businesses));
}
}.execute();
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
Business biz = (Business) listView.getItemAtPosition(position);
Log.v("Sending data to Detail","hi "+biz);
//startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(biz.url)));
Intent intent = new Intent(getApplicationContext(), YelpBizDetail.class);
// Intent intent = new Intent(YelpSearch.this,YelpBizDetail.class).putExtra("myCustomerObj",biz);
intent.putExtra("Detailclass",biz);
Log.v("Sending data to Detail","sent "+biz);
startActivity(intent);
}
List<Business> processJson(String jsonStuff) throws JSONException {
JSONObject json = new JSONObject(jsonStuff);
JSONArray businesses = json.getJSONArray("businesses");
ArrayList<Business> businessObjs = new ArrayList<Business>(businesses.length());
for (int i = 0; i < businesses.length(); i++) {
JSONObject business = businesses.getJSONObject(i);
businessObjs.add(new Business(business.optString("name"), business.optString("mobile_url"),business.optString("id")));
}
return businessObjs;
}
}
YelpBizDetail(toClass)
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import com.....projectmaw.YelpSearch.Business;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class YelpBizDetail extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yelp_biz_detail);
Intent i = getIntent();
Business biz = (Business) i.getSerializableExtra("Detailclass");
// String biz = (String) i.getSerializableExtra("Detailclass");
//String biz = (String) i.getSerializableExtra("Detailclass");
Log.v("Received on Detail","data "+biz);
}
}
Try making some changes in onListItemClick in your YelpSearch.java, like change your startActivity(intent) with
startActivity(new Intent(getApplicationContext(), YelpBizDetail.class).putExtra("Detailclass",biz)); this will create new intent when new activity is started. and remove
Log.v("Sending data to Detail","hi "+biz);
//startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(biz.url)));
Intent intent = new Intent(getApplicationContext(), YelpBizDetail.class);
// Intent intent = new Intent(YelpSearch.this,YelpBizDetail.class).putExtra("myCustomerObj",biz);
intent.putExtra("Detailclass",biz);
Log.v("Sending data to Detail","sent "+biz);
Related
im trying to move the info of a user from one activity to the other, but everytime i run the app it crashes at the "startActivity(i)" Line (i checked everything else, it only crashes at that line).
that's the MainActivity Code
package com.example.hw1511;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hw1511.Model.User;
import org.w3c.dom.Text;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements Serializable {
private EditText Name;
private EditText Age;
private EditText Birth;
private Button AddUser;
private Button Send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = findViewById(R.id.Name);
Age = findViewById(R.id.Age);
Birth = findViewById(R.id.Birth);
AddUser = findViewById(R.id.AddUser);
Send = findViewById(R.id.Send);
Intent i = new Intent(MainActivity.this, SecondActivity.class);
List<User> list1 = new LinkedList<>();
AddUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Name.getText().toString().trim().length() > 0 && Age.getText().toString().trim().length() > 0 && Birth.getText().toString().trim().length() > 0) {
User u = new User(Name.getText().toString(), Integer.parseInt(Age.getText().toString()), Birth.getText().toString());
list1.add(u);
Name.setText("");
Age.setText("");
Birth.setText("");
}
else {
Toast.makeText(MainActivity.this, "Fill All", Toast.LENGTH_SHORT).show();
}
}
});
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i.putExtra("Users", (Serializable) list1);
startActivity(i);
}
});
}
}
and that's the SecondActivty Code (it's preety much empty)
package com.example.hw1511;
import androidx.appcompat.app.AppCompatActivity;
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.example.hw1511.Model.User;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.Attributes;
public class SecondActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
please if anyone help me understand what is making my app crash everytime i press the send button! it would really help me a lot.
Your User objects need to implement Serializable as well.
Also, since LinkedLists are Serializable you can use putSerializable(String key, Serializable value) instead of putExtra
im trying to retrieve data from firebase to detail activity. On the listview, it show perfectly. But when i click, the detail activity opened but still empty. All it says "W/ClassMapper: No setter/field for url found on class com.example.scheduletask.model.Task". I thought the setter on model task wasn't used, but i don't know... im sorry, i don't understand, i don't know what i missed:( any help is appreciated, thank youuu
TaskActivity.java
package com.example.scheduletask;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.scheduletask.adapter.MatkulAdapter;
import com.example.scheduletask.adapter.TaskAdapter;
import com.example.scheduletask.adapter.TaskDetailAdapter;
import com.example.scheduletask.database.FirebaseTaskHelper;
import com.example.scheduletask.model.Matkul;
import com.example.scheduletask.model.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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;
import java.util.Iterator;
public class TaskActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ListView listViewTask;
FloatingActionButton fabAddTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
databaseReference = FirebaseDatabase.getInstance().getReference("Task");
listViewTask = findViewById(R.id.tasklist);
showData();
fabAddTask = findViewById(R.id.fab_addtask);
fabAddTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TaskActivity.this, CreateTaskActivity.class);
startActivity(intent);
}
});
listViewTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String subjectTask = ((TextView)view.findViewById(R.id.txt_subjectlisttask)).getTag().toString();
Intent taskDetail = new Intent(TaskActivity.this, TaskDetailActivity.class);
taskDetail.putExtra("subjectTask", subjectTask);
startActivity(taskDetail);
}
});
}
private void showData() {
final ArrayList<String> subjectTask = new ArrayList<>();
final ArrayList<String> taskDueDate = new ArrayList<>();
final ArrayList<String> taskDescription = new ArrayList<>();
final ArrayList<String> imageURL = new ArrayList<>();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
Iterator<DataSnapshot> iterator = snapshotIterable.iterator();
while (iterator.hasNext()){
Task value = iterator.next().getValue(Task.class);
assert value != null;
subjectTask.add(value.getSubjectTask());
taskDescription.add(value.getTaskDescription());
taskDueDate.add(value.getTaskDueDate());
imageURL.add(value.getImageURL());
((TaskAdapter)listViewTask.getAdapter()).notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
listViewTask.setAdapter(new TaskAdapter(subjectTask, taskDescription, taskDueDate, imageURL, this));
}
#Override
protected void onResume() {
super.onResume();
showData();
}
}
Task.java (this is the model)
package com.example.scheduletask.model;
public class Task {
private String taskDueDate;
public String getTaskDueDate() {
return taskDueDate;
}
public void setTaskDueDate(String taskDueDate) {
this.taskDueDate = taskDueDate;
}
private String subjectTask;
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
private String taskDescription;
private String imageURL;
public String getSubjectTask() {
return subjectTask;
}
public void setSubjectTask(String subjectTask) {
this.subjectTask = subjectTask;
}
}
TaskDetailActivity.java
package com.example.scheduletask;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.scheduletask.model.Task;
import com.github.barteksc.pdfviewer.PDFView;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class TaskDetailActivity extends AppCompatActivity {
EditText edtSubject, edtDueDate, edtDescription;
ImageView filePhoto;
ProgressBar progressBarDetail;
Button btnEdit, btnDelete;
DatabaseReference databaseReference;
private String photoURL, subjectTask;
Button btnViewPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_detail);
databaseReference = FirebaseDatabase.getInstance().getReference("Task");
subjectTask = getIntent().getExtras().getString("subjectTask");
progressBarDetail = findViewById(R.id.progressbardetail);
progressBarDetail.setVisibility(View.INVISIBLE);
readData();
findAllViewsID();
}
private void readData() {
progressBarDetail.setVisibility(View.VISIBLE);
Query findQuery = databaseReference.orderByKey().equalTo(subjectTask);
findQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot getSnapshot : dataSnapshot.getChildren()){
edtSubject.setText(getSnapshot.child("subjectTask").getValue().toString());
edtDescription.setText(getSnapshot.child("taskDescription").getValue().toString());
edtDueDate.setText(getSnapshot.child("taskDueDate").getValue().toString());
photoURL = getSnapshot.child("imageURL").getValue().toString();
Picasso.get().load(photoURL).fit().into(filePhoto);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressBarDetail.setVisibility(View.INVISIBLE);
}
});
progressBarDetail.setVisibility(View.INVISIBLE);
}
private void findAllViewsID() {
edtSubject = findViewById(R.id.edt_updatetasksubject);
edtDescription = findViewById(R.id.edt_updatetaskdescription);
edtDueDate = findViewById(R.id.edt_updateduedatetime);
filePhoto = findViewById(R.id.iv_taskphotoinput);
btnViewPDF = findViewById(R.id.btn_viewpdf);
btnDelete = findViewById(R.id.btn_deletetask);
btnEdit = findViewById(R.id.btn_edittask);
}
}
TaskAdapter.java
package com.example.scheduletask.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.scheduletask.R;
import com.example.scheduletask.TaskActivity;
import com.example.scheduletask.TaskDetailActivity;
import com.example.scheduletask.model.Task;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class TaskAdapter extends BaseAdapter {
private ArrayList<String> subjectTask;
private ArrayList<String> taskDescription;
private ArrayList<String> taskDueDate;
private ArrayList<String> imageURL;
private AppCompatActivity activity;
public TaskAdapter(ArrayList<String> subjectTask, ArrayList<String> taskDescription, ArrayList<String> taskDueDate, ArrayList<String> imageURL, AppCompatActivity activity) {
this.subjectTask = subjectTask;
this.taskDescription = taskDescription;
this.taskDueDate = taskDueDate;
this.imageURL = imageURL;
this.activity = activity;
}
Context ctx;
ArrayList<Task> tasks;
#Override
public int getCount() {
return subjectTask.size();
}
#Override
public Object getItem(int position) {
return subjectTask.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public TaskAdapter(#NonNull Context ctx, ArrayList<Task> tasks) {
this.ctx = ctx;
this.tasks = tasks;
}
public View getView(int position, View view, ViewGroup parent) {
view = LayoutInflater.from(activity.getApplicationContext())
.inflate(R.layout.list_task, parent, false);
view.findViewById(R.id.txt_subjectlisttask).setTag(String.valueOf(subjectTask.get(position)));
((TextView)view.findViewById(R.id.txt_subjectlisttask)).setText(String.valueOf(subjectTask.get(position)));
((TextView)view.findViewById(R.id.txt_duedatetasklist)).setText(String.valueOf(taskDueDate.get(position)));
return view; }
}
Here is the logcat when i click the task listview
And this is my database
How do I get the json result from onPostExecute to another activity? I was able to get the user details from the database based on the username logged in. So in my HomePageActivity there is a button to go to profile and when I clicked on btnprofile it displays the user details on textviews in the current activity(HomePageActivity) but what I wanted to do is to get the user details and then display it to a new activity, which is in the Profile Activity. I tried using Intent but when I go to Profile Activity it displays nothing. Can you please help me? :(
Here is my HomePageActivity:
package com.example.androidmp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.content.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import com.example.androidmp.User;
import java.util.ArrayList;
import java.util.List;
import com.example.androidmp.User;
import com.example.androidmp.Poem;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class HomePageActivity extends Activity {
Button btnfeed, btnprofile;
User u = new User();
String Username,Password,Fullname,Email,Location,Bio,uname;
String getusername,getpw,getfn,getem,getloc,getb;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, String> hashMap = new HashMap<String, String>();
Intent i;
Bundle bundle;
private static final String USERNAME = "Username";
private static final String PASSWORD = "Password";
private static final String FULLNAME = "Fullname";
private static final String EMAIL = "Email";
private static final String BIO = "Bio";
private static final String LOCATION = "Location";
String s="";
TextView fn,em,loc,b;
private static final String TAG_PROFILE = "user";
private static final String PROFILE_URL = "http://192.168.1.5/webservices/mycontroller/getUser.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Intent intent = getIntent();
u.SetUsername(intent.getStringExtra(u.username()));
fn = (TextView) findViewById(R.id.textView1);
em = (TextView) findViewById(R.id.textView2);
loc = (TextView) findViewById(R.id.textView3);
b = (TextView) findViewById(R.id.textView4);
TextView textView = (TextView) findViewById(R.id.getusername);
textView.setText(u.getUsername());
uname = u.getUsername().toString();
//uname = textView.toString();
//u.SetUsername(uname.toString());
btnprofile = (Button) findViewById(R.id.btnprofile);
btnfeed = (Button) findViewById(R.id.btnfeed);
//getem = em.getText().toString();
//getloc = loc.getText().toString();
//getb = b.getText().toString();
btnprofile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ProfileAsync().execute();
Intent i = new Intent(HomePageActivity.this,ProfileActivity.class);
i.putExtra("fullname",Fullname);
i.putExtra("email", Email);
i.putExtra("bio", Bio);
i.putExtra("location", Location);
startActivity(i);
finish();
}
});
btnfeed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a = new Intent(HomePageActivity.this,FeedActivity.class);
startActivity(a);
}
});
}
class ProfileAsync extends AsyncTask<String, String, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(HomePageActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String json=null;
byte[] data;
StringBuffer buffer = null;
InputStream is = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", uname));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PROFILE_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
Log.e("Profile JSON: ", json.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json){
super.onPostExecute(json);
loadingDialog.dismiss();
try
{
jsonobject = new JSONObject(json);
jsonarray = jsonobject.getJSONArray("user");
JSONObject jb= jsonarray.getJSONObject(0);
//Username = jb.getString("Username");
//Password = jb.getString("Password");
Fullname = jb.getString("Fullname");
Email = jb.getString("Email");
Bio = jb.getString("Bio");
Location = jb.getString("Location");
fn.setText(Fullname);
em.setText(Email);
loc.setText(Location);
b.setText(Bio);
}catch(Exception e)
{
e.printStackTrace();
}
}
}//end of asynctask
}
Here is my ProfileActivity:
package com.example.androidmp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.content.*;
import com.example.androidmp.User;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
public class ProfileActivity extends Activity {
Button btncreate;
private TextView _username,_password,_fullname,_Email,_bio,_location;
User u = new User();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profileview);
//_username = (TextView) findViewById(R.id._username);
//_password = (TextView) findViewById(R.id._password);
_fullname = (TextView) findViewById(R.id._fullname);
_Email = (TextView) findViewById(R.id._Email);
_bio = (TextView) findViewById(R.id._bio);
_location = (TextView) findViewById(R.id._location);
Intent i = getIntent();
u.SetUsername(i.getStringExtra(u.username()));
_username.setText(u.getUsername());
String displayfullname = i.getExtras().getString("fullname");
String displayemail = i.getExtras().getString("email");
String displaybio = i.getExtras().getString("bio");
String displaylocation = i.getExtras().getString("location");
_fullname.setText(displayfullname);
_Email.setText(displayemail);
_bio.setText(displaybio);
_location.setText(displaylocation);
}
}
It is because new activity starts before async task is completed. Just call function for start new activity in onPostExecute() function.
Pass values after fetching the details. Is the settext working properly? then you can give the intent at that scope, in the onPostexecute method. Look before doing this.Look this
I have some dummy problem, I need to get Spinner Item Position from the Fragment to this class:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.objects.Person;
import com.example.nortti.politrange.objects.Site;
import com.example.nortti.politrange.utils.WebApiAdapter;
import com.example.nortti.politrange.views.GeneralFragment;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class PersonCatalog implements ICatalog{
private final String COMMAND_PREFIX = "/api/stats/1";
private final WebApiAdapter apiAdapter = new WebApiAdapter(COMMAND_PREFIX);
private ArrayList<Person> catalogList = new ArrayList<Person>();
private Site site;
public PersonCatalog(Site site) {
this.site = site;
}
#Override
public ArrayList<Person> getCatalogList() {
return catalogList;
}
public void populateData() {
JSONArray jsonObject = null;
try {
jsonObject = (JSONArray)(new JSONParser()).parse(apiAdapter.select(null));
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
catalogList.clear();
Iterator<JSONObject> iterator = jsonObject.iterator();
while(iterator.hasNext()) {
JSONObject o = iterator.next();
catalogList.add(new Person((String)o.get("personName"),(int)(long)o.get("rank")));
}
}
}
I broke my head, I don't know how to do it. Please help! Should I use some Intents or create some getters?
UPD: Fragment Code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.adapters.GenAdapter;
import com.example.nortti.politrange.adapters.SiteAdapter;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.intefaces.impls.PersonCatalog;
import com.example.nortti.politrange.intefaces.impls.SitesCatalog;
import com.example.nortti.politrange.objects.Site;
public class GeneralFragment extends Fragment implements OnClickListener, OnItemSelectedListener {
private Button genApply;
private Spinner spinner;
private ListView genList;
private View header;
private ICatalog siteCatalogImpl;
private ICatalog personCatalogImpl;
public int Num;
public void setSpinnerSource(ICatalog siteCatalogImpl) {
this.siteCatalogImpl = siteCatalogImpl;
spinData();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.general_fragment, container,false);
header = inflater.inflate(R.layout.gen_head, null);
spinner = (Spinner) v.findViewById(R.id.wSpin);
spinner.setOnItemSelectedListener(this);
genApply = (Button) v.findViewById(R.id.genApply);
genApply.setOnClickListener(this);
genList = (ListView) v.findViewById(R.id.genList);
genList.addHeaderView(header);
this.setSpinnerSource(new SitesCatalog());
Intent i = new Intent();
i.putExtra("spin", spinner.getSelectedItemPosition()+1);
return v;
}
private void spinData() {
siteCatalogImpl.populateData();
spinner.setAdapter(new SiteAdapter(getActivity(), siteCatalogImpl.getCatalogList()));
}
private void listData(Site site) {
personCatalogImpl = new PersonCatalog(site);
personCatalogImpl.populateData();
genList.setAdapter(new GenAdapter(getActivity(), personCatalogImpl.getCatalogList()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
int siteIndex = spinner.getSelectedItemPosition();
switch (v.getId()) {
case R.id.genApply:
listData((Site)siteCatalogImpl.getCatalogList().get(siteIndex));
break;
}
}
}
I calling PersonCatalog at the listdata method.
Try this.
final ArrayList<String> providerlist= new ArrayList<String>();
Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = providerlist.get(position);
// Showing selected spinner item
Toast.makeText(this,
"Selected Country : " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I am wondering why I am getting the following logcat when I run my app and try and click on the Daily Forecast option.
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.ListView
HERE IS MY DAILYFORECASTACTIVITY
package com.dredaydesigns.stormy.ui;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.dredaydesigns.stormy.R;
import com.dredaydesigns.stormy.adapters.DayAdapter;
import com.dredaydesigns.stormy.weather.Day;
import java.util.Arrays;
public class DailyForecastActivity extends ListActivity {
private Day[] mDays;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
Intent intent = getIntent();
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
mDays = Arrays.copyOf(parcelables, parcelables.length, Day[].class);
DayAdapter adapter = new DayAdapter(this, mDays);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String dayOfTheWeek = mDays[position].getDayOfTheWeek();
String conditions = mDays[position].getSummary();
String highTemp = mDays[position].getTemperatureMax() + "";
String message = String.format("On %s the high will be %s and it will be %s", dayOfTheWeek, highTemp, conditions);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
EDIT: SORRY FORGOT TO POST THIS!HERE IS ACTIVITY DAILY FORECAST
'package com.dredaydesigns.stormy.ui;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.dredaydesigns.stormy.R;
import com.dredaydesigns.stormy.adapters.DayAdapter;
import com.dredaydesigns.stormy.weather.Day;
import java.util.Arrays;
import butterknife.ButterKnife;
public class DailyForecastActivity extends ListActivity {
private Day[] mDays;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
ButterKnife.inject(this);
Intent intent = getIntent();
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
mDays = Arrays.copyOf(parcelables, parcelables.length, Day[].class);
DayAdapter adapter = new DayAdapter(this, mDays);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String dayOfTheWeek = mDays[position].getDayOfTheWeek();
String conditions = mDays[position].getSummary();
String highTemp = mDays[position].getTemperatureMax() + "";
String message = String.format("On %s the high will be %s and it will be %s", dayOfTheWeek, highTemp, conditions);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
'
Do I need to declare the ListActivity differently?
Set the id of your ListView id as #android:id/list and then your onCreate method will be
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
Intent intent = getIntent();
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
mDays = Arrays.copyOf(parcelables, parcelables.length, Day[].class);
DayAdapter adapter = new DayAdapter(this, mDays);
setListAdapter(adapter);
}