Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am working on a project where I have to display a list of available Professors for a department. Instead of displaying all professors, I want to allow a student to search professors by Department. As a result, the student will logs in, search for a professor based on name, department, course ID, or all. I am using a custom list adapter. I noticed that Adapter object is not null, but the list is still showing "No records available to display. I think the issue has to do with the way that I am setting the adapter in the ProfessorDetail class. What am I doing wrong here?
See codes below:
Professors Class
package com.mb.professor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.mb.professor.asynctasks.ProfessorAsyncTask;
/**
* Created by Gagouche on 7/25/13.
*/
public class Professors extends FragmentActivity {
private Button bSearch;
private EditText etSearchBy;
private EditText etCourseId;
private Spinner spSearchDecision;
private String searchValue = null;
private Professor[] _professor = null;
public Professors()
{
}
public Professors(Professor[] professor)
{
this._professor = professor;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.professor);
InitialVariables();
}
private void InitialVariables()
{
bSearch = (Button) this.findViewById(R.id.bSearch);
etSearchBy = (EditText) this.findViewById(R.id.etSearchByDepartment);
etCourseId = (EditText) this.findViewById(R.id.etSearchByCouseId);
spSearchDecision = (Spinner) this.findViewById(R.id.spOption);
bSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(searchValue == "Department")
{
ProfessorAsyncTask professor = new ProfessorAsyncTask();
professor.execute("");
FragmentManager mFragment = getSupportFragmentManager();
FragmentTransaction ft = mFragment.beginTransaction();
ProfessorDetail pDetail = new ProfessorDetail();
pDetail.setProfessorAdapter(_professor);
ft.replace(R.id.fprofessorDetail, pDetail);
ft.addToBackStack(null);
ft.commit();
}
}
});
spSearchDecision.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position)
{
case 0:
searchValue = "By All";
break;
case 1:
searchValue = "Department";
break;
case 2:
searchValue = "CourseId";
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
searchValue = "By All";
}
});
}
}
ProfessorDetail Class
package com.mb.professor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.mb.professor.adapter.*;
/**
* Created by Gagouche on 7/25/13.
*/
public class ProfessorDetail extends ListFragment {
private ProfessorAdapter adapter = null;
Professor[] prof = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void setProfessorAdapter(Professor[] professor)
{
prof = professor;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String [] emptyAdapter = {};
if(prof == null)
{
ArrayAdapter<String> emptyListAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,emptyAdapter);
setListAdapter(emptyListAdapter);
} else
{
adapter = new ProfessorAdapter(getActivity(), R.layout.professor_row, prof);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.customizelayout, container, false);
}
}
Course Detail Class
package com.mb.professor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.mb.professor.adapter.CourseAdapter;
import java.util.List;
/**
* Created by Gagouche on 7/25/13.
*/
public class CourseDetail extends ListFragment {
private CourseAdapter adapter = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void setCourseData(Course[] course)
{
adapter = new CourseAdapter(getActivity(), R.layout.course_row, course);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] course = {};
if(adapter == null)
{
ArrayAdapter<String> emptyAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1 , course );
setListAdapter(adapter);
} else
{
setListAdapter(adapter);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.customizelayout, container, false);
}
}
Login Course
package com.mb.professor;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Login extends Activity implements View.OnClickListener {
Button btnLogin;
EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initializeVariables();
}
private void initializeVariables()
{
btnLogin = (Button) this.findViewById(R.id.btnLogin);
etUsername = (EditText) this.findViewById(R.id.etUserName);
etPassword = (EditText) this.findViewById(R.id.etPassword);
btnLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
String uName = etUsername.getText().toString();
String pWord = etPassword.getText().toString();
if(uName.equals("college") && pWord.equals("florida"))
{
Intent intent = new Intent(this, Professors.class);
startActivity(intent);
}
}
}
Professor AsyncTask
package com.mb.professor.asynctasks;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import com.mb.professor.Course;
import com.mb.professor.Professor;
import com.mb.professor.ProfessorDetail;
import com.mb.professor.Professors;
import com.mb.professor.R;
/**
* Created by Gagouche on 8/1/13.
*/
public class ProfessorAsyncTask extends AsyncTask<String,Void,Professor[]> {
private FragmentActivity fActivity;
public ProfessorAsyncTask()
{
}
#Override
protected Professor[] doInBackground(String... params) {
Professor[] professor = new Professor[5];
professor[0] = new Professor("Finance", "John", "123", "Accounting");
professor[1] = new Professor("Accounting", "Cain", "124", "finance");
professor[2] = new Professor("Database", "Eugene", "125", "Music");
professor[3] = new Professor("Finance", "Seikei", "126", "Engineer");
professor[4] = new Professor("Finance", "Bojok", "127", "Math");
return professor;
}
#Override
protected void onPostExecute(Professor[] professors) {
super.onPostExecute(professors);
// ProfessorDetail professorDetailFragment = (ProfessorDetail)fActivity.getSupportFragmentManager().findFragmentById(R.id.fprofessorDetail);
// Professors prof = new Professors(professors);
}
}
Course AsyncTask
package com.mb.professor.asynctasks;
import android.app.FragmentTransaction;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import com.mb.professor.Course;
import com.mb.professor.CourseDetail;
import com.mb.professor.R;
import java.util.List;
/**
* Created by Gagouche on 8/1/13.
*/
public class CourseAsyncTask extends AsyncTask<String, Void, Course[]> {
private FragmentActivity mActivity;
private Course[] course = null;
public CourseAsyncTask(FragmentActivity activity)
{
this.mActivity = activity;
}
#Override
protected Course[] doInBackground(String... params) {
Course[] course = new Course[5];
course[0] = new Course("Finance", "John", "123");
course[1] = new Course("Accounting", "Cain", "124");
course[2] = new Course("Database", "Eugene", "125");
course[3] = new Course("Finance", "Seikei", "126");
course[4] = new Course("Finance", "Bojok", "127");
return course;
}
#Override
protected void onPostExecute(Course[] courses) {
super.onPostExecute(courses);
CourseDetail courseDetailFragment = (CourseDetail) mActivity.getSupportFragmentManager().findFragmentById(R.id.fCourseDetail);
courseDetailFragment.setCourseData(courses);
}
}
Professor Adapter
package com.mb.professor.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.mb.professor.*;
import java.util.List;
/**
* Created by Gagouche on 8/1/13.
*/
public class ProfessorAdapter extends ArrayAdapter<Professor> {
private Context context;
private int layoutResourceId;
private Professor[] data = null;
public ProfessorAdapter(Context context, int layoutResourceId, Professor[] data) {
super(context, layoutResourceId, data);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ProfessorHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId,parent, false);
holder = new ProfessorHolder();
holder.tvFirstName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLastName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCourse = (TextView) row.findViewById(R.id.tvCourseID);
holder.tvDepartment = (TextView) row.findViewById(R.id.tvDepartment);
row.setTag(holder);
} else
{
holder = (ProfessorHolder) row.getTag();
}
Professor item = data[position];
holder.tvFirstName.setText(item.getFirstName());
holder.tvLastName.setText(item.getLastName());
holder.tvDepartment.setText(item.getDepartmentID());
holder.tvCourse.setText(item.getCourseId());
return row;
}
static class ProfessorHolder
{
TextView tvFirstName;
TextView tvLastName;
TextView tvDepartment;
TextView tvCourse;
}
}
Course Adapter
package com.mb.professor.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.mb.professor.Course;
import com.mb.professor.R;
/**
* Created by Gagouche on 8/1/13.
*/
public class CourseAdapter extends ArrayAdapter<Course> {
private Context context;
private int layoutResourceId;
private Course[] data = null;
public CourseAdapter(Context context, int resource, Course[] data) {
super(context, resource, data);
this.context = context;
this.layoutResourceId = resource;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CourseHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CourseHolder();
holder.tvCourseInstructor = (TextView) row.findViewById(R.id.tvCourseInstructor);
holder.tvCourseId = (TextView) row.findViewById(R.id.tvCourse);
holder.tvCourseName = (TextView) row.findViewById(R.id.tvCourseName);
row.setTag(holder);
} else {
holder = (CourseHolder) row.getTag();
}
Course item = data[position];
holder.tvCourseId.setText(item.getCourseId());
holder.tvCourseName.setText(item.getCourseName());
holder.tvCourseInstructor.setText(item.getInstructorName());
return row;
}
static class CourseHolder
{
TextView tvCourseName;
TextView tvCourseInstructor;
TextView tvCourseId;
}
}
Login XML
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"
android:textSize="30sp"
/>
<EditText
android:layout_width="200sp"
android:layout_height="wrap_content"
android:id="#+id/etUserName"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:id="#+id/textView2"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:textSize="30sp"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/etPassword"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/btnLogin"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</LinearLayout>
Professor XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search For Professor"
android:id="#+id/textView"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textSize="30sp"
/>
<EditText
android:layout_width="250dp"
android:layout_height="wrap_content"
android:hint="search by Department"
android:id="#+id/etSearchByDepartment"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by Course ID"
android:id="#+id/textView2"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textSize="30sp"
/>
<EditText
android:layout_width="250dp"
android:layout_height="wrap_content"
android:id="#+id/etSearchByCouseId"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
/>
<Spinner
android:layout_width="321dp"
android:layout_height="wrap_content"
android:id="#+id/spOption"
android:entries="#array/searchOption"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
/>
<Button
android:id="#+id/bSearch"
android:text="Search"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"
android:orientation="vertical"
>
<fragment
android:layout_width="match_parent"
android:layout_height="0dp"
android:name="com.mb.professor.ProfessorDetail"
android:id="#+id/fprofessorDetail"
android:layout_weight="1"
android:layout_gravity="center"/>
<fragment
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:name="com.mb.professor.CourseDetail"
android:id="#+id/fCourseDetail"
android:layout_gravity="center"/>
</LinearLayout>
</LinearLayout>
Professor Row Custom XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Name"
android:layout_marginLeft="10dp"
android:id="#id/tvFirstName"
android:layout_gravity="center_horizontal|top"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last Name"
android:layout_marginLeft="10dp"
android:id="#id/tvFirstName"
android:layout_gravity="center_horizontal|top"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:layout_marginLeft="10dp"
android:id="#id/tvDepartment"
android:layout_gravity="center_horizontal|top"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="New Text"
android:id="#id/tvCourseID"
android:layout_gravity="center_horizontal|top"/>
</LinearLayout>
Customize Layout for the ListViews
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"/>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Record to be displayed."
android:textSize="25sp"
android:layout_gravity="left|center_vertical"/>
</LinearLayout>
Here is the exception:
08-05 13:26:25.619 716-731/com.android.exchange D/ExchangeService: Received deviceId from Email app: null
08-05 13:26:25.619 716-731/com.android.exchange D/ExchangeService: !!! deviceId unknown; stopping self and retrying
08-05 13:26:27.242 1055-1055/com.mb.professor D/AndroidRuntime: Shutting down VM
08-05 13:26:27.242 1055-1055/com.mb.professor W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-05 13:26:27.302 1055-1055/com.mb.professor E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:154)
at android.widget.ArrayAdapter.(ArrayAdapter.java:128)
at com.mb.professor.adapter.ProfessorAdapter.(ProfessorAdapter.java:23)
at com.mb.professor.ProfessorDetail.setProfessorAdapter(ProfessorDetail.java:23)
at com.mb.professor.Professors$1.onClick(Professors.java:57)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Am I mistaking ? but you call notifyDataSetChange before the asynctask is finished. You have to call notifyDataSetChange in the onPostExecute of your async task. And therefore your list is empty.
In your code you do in the Professor detail class
adapter = new ProfessorAdapter(getActivity(), R.layout.professor_row, prof);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
you notify the data change and link the adapter to the list. But you never do it again. Your onPost Execute is empty.
What you have to do is move the adapter.notifyDataSetChanged(); to the onPostExecute and your list will be refreshed.
EDIT
Let me show you an example of my code.
public class MyAsyncTaskFragment extends Fragment {
private ListView lv;
private CustomAdapter adapter;
private ArrayList<...your custom type here...> listItems = new ArrayList<...your custom type here...>();
...
#Override
public void onActivityCreated (Bundle savedInstanceState){
//get the listView
lv = (ListView) getView().findViewById(R.id.my_listview_name);
//create new adapter
adapter = new CustomAdapter();
//link adapter to listview
lv.setAdapter(adapter);
//in my case I want the async task to start over when the activity is created
new DoAsyncTask().execute();
}
private class DoAsyncTask extends AsyncTask<Void, Integer, Integer>{
protected void onPreExecute() {
listItems.clear();
}
protected Integer doInBackground(Void...voids) {
//add items to the list
listItems.add(...your custom type here ...);
return null;
}
protected void onPostExecute(Integer result) {
if (listItems.size() > 0){
adapter.notifyDataSetChanged();
}
}
}
}
Related
When i try to put my Expandable layout to the bottom of my cardview using
android:layout_gravity="bottom" it goes to the bottom but expands upwards
After clicking the relative layout "button"
I am getting data from arraylist passing it to the recyclerview and cardview
i don't know if it's because of the Adapter animation settings or just fomr the xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_gravity="top"
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginEnd="8dp"
android:layout_marginBottom="551dp"
android:animateLayoutChanges="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/holderimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView5"
android:layout_width="68dp"
android:layout_height="62dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
app:srcCompat="#drawable/s1960678" />
<TextView
android:id="#+id/nameArray"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:fontFamily="serif"
android:includeFontPadding="false"
android:text="TextView"
android:textSize="14sp"
android:textStyle="bold" />
<RelativeLayout
android:id="#+id/button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp"
android:background="#drawable/ic_arrow_drop_down_black_24dp"
android:foregroundGravity="right"
android:gravity="right|center_horizontal"
android:orientation="vertical">
<View
android:id="#+id/view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<com.github.aakira.expandablelayout.ExpandableLinearLayout
android:id="#+id/expandableLayout"
android:layout_width="match_parent"
android:layout_height="72dp"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:foregroundGravity="bottom"
android:gravity="top"
android:orientation="vertical"
app:ael_duration="400"
app:ael_expanded="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/button3"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:text="Button"
tools:text="Download .PDF" />
<Button
android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
tools:text="View PDF" />
</LinearLayout>
</com.github.aakira.expandablelayout.ExpandableLinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
and here's the activity it gets data from , it's xml has only recyclerview
package com.example.imc.PDF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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.example.imc.MainAdapter;
import com.example.imc.MySingleton;
import com.example.imc.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Resultsdwldview extends AppCompatActivity {
public RequestQueue requestQueue;
TextView MedicalText,PhoneText,AddressText,EmailText,result,resultArray;
EditText id;
Button getidbtn;
List<ArrayList<String>> Tests = new ArrayList<>();
ArrayList<String> urlArray = new ArrayList<String>();
ArrayList<String> nameArray = new ArrayList<String>();
ArrayList<String> IdfromjsonArray = new ArrayList<String>();
ArrayList<String> Patient_ID_Array = new ArrayList<String>();
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
WebView webView;
String PDFurl;
String idvalue;
String url = "https://docs.google.com/viewer?url=http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resultsdwldview);
MedicalText = findViewById(R.id.MedicalText);
PhoneText = findViewById(R.id.PhoneText);
AddressText = findViewById(R.id.AddressText);
EmailText = findViewById(R.id.EmailText);
// webView = findViewById(R.id.webview); //WEBVIEW
// webView.requestFocus();
// webView.getSettings().setJavaScriptEnabled(true);
// webView.loadUrl(url);
mRecyclerView = findViewById(R.id.recyvlerView);
// id = findViewById(R.id.getid);
// getidbtn =(Button) findViewById(R.id.send);
mLayoutManager = new LinearLayoutManager(this);
jsonParse();
/*
getidbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//idvalue = id.getEditableText().toString();
jsonParse();
}
});*/
}
public void jsonParse() {
String URL="http://ashaaban-001-site1.btempurl.com/api/patients/"+4;
//String URL="http://ashaaban-001-site1.btempurl.com/api/patients/"+idvalue;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Tests");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject arraydata = jsonArray.getJSONObject(i);
// Tests.add(jsonObject.getString(String.valueOf(i)));
String urlName = arraydata.getString("urlName");
String Name =arraydata.getString("Name");
String Idfromjson =arraydata.getString("Id");
String P_ID_Array =arraydata.getString("patients_Id");
urlArray.add(urlName);
nameArray.add(Name);
IdfromjsonArray.add(Idfromjson);
Patient_ID_Array.add(P_ID_Array);
Tests.add(urlArray);
Tests.add(nameArray);
Tests.add(IdfromjsonArray);
Tests.add(Patient_ID_Array);
// resultArray.append("urlName = " +urlName+" \n\n Name"+Name);
}
//resultArray.append(Tests+" , \n ");
// mRecyclerView.setHasFixedSize(true);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Integer P_MedicalNumber = response.getInt("MedicalNumber");
Integer P_id = response.getInt("Id");
String P_Username = response.getString("UserName");
Integer P_PhoneNumber = response.getInt("phoneNumber");
String P_Address = response.getString("Address");
String P_Email = response.getString("Email");
//result.append("Medical Number : "+P_MedicalNumber+" \n id :"+P_id+"UserName"+P_Username);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter = new MainAdapter(Tests,nameArray);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyItemRangeInserted(0, Tests.size());
// webView.loadUrl(PDFurl);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
});
// requestQueue.add(request);
MySingleton.getInstance(Resultsdwldview.this).addToReqeustQueue(jsonObjectRequest);
}
}
Adapter
package com.example.imc;
import android.animation.ObjectAnimator;
import android.content.ClipData;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.aakira.expandablelayout.ExpandableLayout;
import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter;
import com.github.aakira.expandablelayout.ExpandableLinearLayout;
import com.github.aakira.expandablelayout.Utils;
import java.util.ArrayList;
import java.util.List;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
List<ArrayList<String>> Tests;
ArrayList<String> urlArray;
ArrayList<String> nameArray;
ArrayList<String> IdfromjsonArray ;
ArrayList<String> Patient_ID_Array;
SparseBooleanArray expandState =new SparseBooleanArray();
public MainAdapter(List<ArrayList<String>> tests, ArrayList<String> urlArray, ArrayList<String> nameArray,
ArrayList<String> idfromjsonArray, ArrayList<String> patient_ID_Array) {
Tests = tests;
this.urlArray = urlArray;
this.nameArray = nameArray;
IdfromjsonArray = idfromjsonArray;
Patient_ID_Array = patient_ID_Array;
}
public MainAdapter(List<ArrayList<String>> tests, ArrayList<String> nameArray) {
Tests = tests;
this.nameArray = nameArray;
}
#NonNull
#Override
//Initialize the viewholder
public MainAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row,viewGroup,false);
return new ViewHolder(view);
}
/***************////////////////onBind Holds values to pass it to the viewholder///////////////////*******************
/***************////////////////
// This method is called for each ViewHolder to
// bind it to the adapter
// . This is where we will// pass our data to our ViewHolder///////////////////*******************
#Override
public void onBindViewHolder(#NonNull final MainAdapter.ViewHolder holder, final int i) {
// holder.URLName.setText( urlArray.get(i));
holder.mFullname.setText( nameArray.get(i));
holder.expandableLayout.setInRecyclerView(true);
holder.expandableLayout.setExpanded(expandState.get(i));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
changeRotate(holder.button,180f,0f).start();
expandState.put(i,true);
}
#Override
public void onPreClose() {
changeRotate(holder.button,0f,180f).start();
expandState.put(i,false);
}
});
holder.button.setRotation(expandState.get(i)?0f:180f);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Expandable child item
holder.expandableLayout.toggle();
}
});
}
private ObjectAnimator changeRotate(RelativeLayout button, float to, float from) {
ObjectAnimator animator = ObjectAnimator.ofFloat(button,"rotation",from,to);
animator.setDuration(200);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
#Override
public int getItemCount() {
return nameArray.size();
}
/***************////////////////VIEWHOLDER///////////////////*******************
public class ViewHolder extends RecyclerView.ViewHolder {
// public TextView URLName;
public TextView mFullname;
public RelativeLayout button;
public ExpandableLinearLayout expandableLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mFullname=itemView.findViewById(R.id.nameArray);
//URLName=itemView.findViewById(R.id.URLName);
button=itemView.findViewById(R.id.button);
expandableLayout=itemView.findViewById(R.id.expandableLayout);
}
}
}
every one,
I am a beginning learner on android system ,
I create a small app that could get specific data , like foreign exchange rate from bank website ,
this app uses Jsoup , ListView , BaseAdapter etc...
finally , the only problem is the listView has no any display ,
could any one tell me , how to fix it.
Thanks.
Category.java
public class Category
{
String bank_name;
String page_url;
Category(String bank_name,String url)
{
this.bank_name=bank_name;
this.page_url=url;
}
#Override
public String toString()
{
return bank_name;
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity
{
ArrayList<Category> items;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<Category>();
items.add(new Category("台灣銀行","http://rate.bot.com.tw/Pages/Static/UIP003.zh-TW.htm"));
ArrayAdapter<Category> adapter = new ArrayAdapter<Category>(this , android.R.layout.simple_list_item_1 ,items);
ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(adapter);
lv.setOnItemClickListener(itemClick);
}
OnItemClickListener itemClick = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> av , View v , int position , long id)
{
Category category = items.get(position);
Intent intent = new Intent();
intent.setClass(MainActivity.this , RateActivity.class );
intent.putExtra("bank_name", category.bank_name);
intent.putExtra("page_url" , category.page_url);
startActivity(intent);
}
};
RateBean.java
public class RateBean
{
private String currency;
private String cashBuy;
private String cashSold;
private String spotBuy;
private String spotSold;
public RateBean()
{
currency = "";
cashBuy = "";
cashSold = "";
spotBuy = "";
spotSold = "";
}
public RateBean(String [] strArr)
{
this.currency=strArr[0];
this.cashBuy=strArr[1];
this.cashSold=strArr[2];
this.spotBuy=strArr[3];
this.spotSold=strArr[4];
}
public RateBean(String currency , String cashBuy , String cashSold , String spotBuy ,String spotSold)
{
setCurrency(currency);
setCashBuy(cashBuy);
setCashSold(cashSold);
setSpotBuy(spotBuy);
setSpotSold(spotSold);
}
//Currency setter and getter
public void setCurrency(String currency)
{
this.currency = currency ;
}
public String getCurrency()
{
return currency;
}
//Cash buy setter and getter
public void setCashBuy(String cashBuy)
{
this.cashBuy = cashBuy;
}
public String getCashBuy()
{
return cashBuy;
}
//Cash sold setter and getter
public void setCashSold(String cashSold)
{
this.cashSold = cashSold;
}
public String getCashSold()
{
return cashSold;
}
//Spot buy setter and getter
public void setSpotBuy(String spotBuy)
{
this.spotBuy = spotBuy;
}
public String getSpotBuy()
{
return spotBuy;
}
//Spot sold setter and getter
public void setSpotSold(String spotSold)
{
this.spotSold = spotSold;
}
public String getSpotSold()
{
return spotSold;
}
}
RateActivity.java
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
public class RateActivity extends ListActivity
{
Context context ;
ArrayList<RateBean> rateBean_item;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate_show);
TextView updateTime = (TextView)findViewById(R.id.updateTime_textView);
Intent intent = getIntent();
String category = intent.getStringExtra("bank_name");
String page_url = intent.getStringExtra("page_url");
setTitle(category);
context=this;
ConnectThread thread = new ConnectThread(context , rateBean_item , page_url , updateTime);
thread.start();
}
public class ConnectThread extends Thread
{
Context context;
ArrayList<RateBean> rateBean_item;
String page_url ;
TextView updateTime;
RateAdapter adapter;
RateBean rateBean;
int i =0;
public ConnectThread(Context context , ArrayList<RateBean> rateBean_item , String page_url , TextView updateTime )
{
this.context=context;
this.rateBean_item=rateBean_item;
this.page_url=page_url;
this.updateTime=updateTime;
}
#Override
public void run()
{
try
{
String currency="";
String cashBuy="";
String cashSold="";
String spotBuy="";
String spotSold="";
Document doc = Jsoup.connect(page_url).get();
rateBean_item = new ArrayList<>();
String temp=doc.select("td[style=width:326px;text-align:left;vertical-align:top;color:#0000FF;font-size:11pt;font-weight:bold;]").text();
String time=temp.substring(12);
updateTime.setText("匯率更新時間:\n" + time);
for( Element title:doc.select("td.titleLeft"))
{
currency=title.text();
if( i < doc.select("td.decimal").size())
{
cashBuy=doc.select("td.decimal").eq(i++).text();
cashSold=doc.select("td.decimal").eq(i++).text();
spotBuy=doc.select("td.decimal").eq(i++).text();
spotSold=doc.select("td.decimal").eq(i++).text();
rateBean = new RateBean( a , b , c ,d , e );
rateBean_item.add(rateBean);
}
}
adapter = new RateAdapter(context , rateBean_item);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
catch( Exception exception )
{
exception.printStackTrace();
}
}
}
}
RateAdapter.java
import java.util.ArrayList;
import android.util.Log;
import android.widget.BaseAdapter;
import android.view.*;
import android.widget.*;
import android.content.*;
public class RateAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private ArrayList<RateBean> list ;
public RateAdapter()
{
}
public RateAdapter(Context context , ArrayList<RateBean> list )
{
this.inflater = LayoutInflater.from(context);
this.list = list;
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public static class ViewHolder
{
TextView currency_name;
TextView cash_buy;
TextView cash_sold;
TextView spot_buy;
TextView spot_sold;
}
#Override
public View getView( int position , View convertView , ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = inflater.inflate(R.layout.rate_item , null);
holder = new ViewHolder();
holder.currency_name = (TextView)convertView.findViewById(R.id.xml_currency);
holder.cash_buy = (TextView)convertView.findViewById(R.id.xml_cashBuy);
holder.cash_sold = (TextView)convertView.findViewById(R.id.xml_cashSold);
holder.spot_buy = (TextView)convertView.findViewById(R.id.xml_spotBuy);
holder.spot_sold = (TextView)convertView.findViewById(R.id.xml_spotSold);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
RateBean rateItem = list.get(position);
holder.currency_name.setText(rateItem.getCurrency());
holder.cash_buy.setText(rateItem.getCashBuy());
holder.cash_sold.setText(rateItem.getCashSold());
holder.spot_buy.setText(rateItem.getSpotBuy());
holder.spot_sold.setText(rateItem.getSpotSold());
return convertView;
}
}
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/title_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="銀行查詢選擇"/>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_rate_show.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/updateTime_textView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="updateTime"/>
<Button
android:id="#+id/fresh_button"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="onClick"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/button_fresh"/>
</LinearLayout>>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/currency"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_sold"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_sold"/>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
rate_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/xml_currency"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:textAppearance="?android:attr/textAppearanceLarge"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
</LinearLayout>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Your listview needs a height, it cannot be wrap_content. Give it a height like 500dp or match_parent.
I am trying to create an app that displays the menus of each dining hall at my school. How would I go about parsing this website https://hdh.ucsd.edu/DiningMenus/default.aspx?i=18 or https://hdh.ucsd.edu/DiningMenus/default.aspx?i=18 and getting the menus for breakfast lunch and dinner into a listview that displays on a fragment?
This is the code I have:
ErcFragment.java
import android.view.View;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.os.AsyncTask;
import android.app.ProgressDialog;
import android.widget.TextView;
import java.util.ArrayList;
public class ErcFragment extends Fragment {
// URL Address
String url = "http://hdh.ucsd.edu/mobile/dining/locationdetails.aspx?l=18&no_server_init";
ProgressDialog mProgressDialog;
String MENU;
ListView listview;
TextView textview;
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_erc, container, false);
View view = inflater.inflate(R.layout.fragment_erc, container, false);
textview = (TextView)view.findViewById(R.id.textView10);
new JSOUP().execute();
return rootView;
}
public class JSOUP extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params){
try{
Document document = Jsoup.connect(url).get();
Elements elements = document.select("div[class='message info last']");
for(int i = 0; i<elements.size(); i++){
MENU += "\n" + elements.get(i).text();
}
}
catch (Exception e){
}
return null;
}
#Override
protected void onPostExecute(Void result){
dialog.dismiss();
textview.setText(MENU);
super.onPostExecute(result);
}
}
}
and fragment_erc.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Cafe Ventanas"
android:id="#+id/textView9"
android:layout_gravity="center_horizontal"
android:elegantTextHeight="false"
android:textSize="40dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView10"
android:layout_gravity="center" />
</FrameLayout>
if you are successfuly getting data from server the follow the below code to display it in list fragment-
Here is the example code.
First create a layout for one list row.
example : list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
>
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/merk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/harga"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/merk"
android:layout_marginTop="5dp"/>
</RelativeLayout>
After creating this list_row.xml layout, create a adapter class.
create CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<Barang> barangList;
public CustomListAdapter(Activity activity, ArrayList<Barang> barangList) {
this.activity = activity;
this.barangList = barangList;
}
/*
get count of the barangList
*/
#Override
public int getCount() {
return barangList.size();
}
#Override
public Object getItem(int location) {
return barangList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
/*
inflate the items in the list view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row, null);
}
/*
creating objects to access the views
*/
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView merk = (TextView) convertView.findViewById(R.id.merk);
TextView harga = (TextView) convertView.findViewById(R.id.harga);
// getting barang data for the row
Barang barang = barangList.get(position);
name.setText(barang.getNama_barang());
merk.setText(barang.getMerk_barang());
harga.setText(barang.getHarga_barang());
return convertView;
}}
Now in your MasterBarang.java, put the following code in your onCreate method.
values = dataSource.getAllBarang();
CustomListAdapter adapter;
adapter = new CustomListAdapter(getActivity(), values);
setListAdapter(adapter);
Two issue with List Fragment: 1. I have a class that extends ListFragments.In the onCreated, I am setting my custom Adapter. The issue is that when the user logs in, the adadpter is null and would not have a value until the user searches for an owner. As a result, it throws an exception when it tries to set up the listadapter and it finds the ArrayAdapter object to be null. I have a custome layout that has a listview and a textview, but I still gets the error. See sample code below. I bold the line of code where the issue happens. Also, I bold few other section where I think it may be important to notice.
I implemented Parcelable in the class "Owner" so that I can pass the object as a ParcelableArray. Even though the object is not null, retrieving it in the OwnerDetail class shows null as if I did not pass it it. I've seen several example, but I am not able to get it right. What am I doing wrong here?
Note: If I were to call the AsyncTask in the OwnerDetail class and set the ListAdapter, it will work fine. The issue with that is that it will display a list of owners as soon as the user is logged in which is not the expected behavior. The behavior that I want is to login first, search for an owner, display the owner, double click on an owner, and finally display a list of cars that the owner owns. I am doing this project, so I can learn how to use ListFraments.
// Here is the entire code
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Car implements Parcelable {
private String _make;
private String _model;
private String _year;
public Car()
{
this._make = "";
this._model = "";
this._year = "";
}
public Car(String make)
{
this._make = make;
}
public Car(String make, String year)
{
this._make = make;
this._year = year;
}
public Car(String make, String model, String year)
{
this._make = make;
this._model = model;
this._year = year;
}
//Getters
public String getMake()
{
return _make;
}
public String getModel()
{
return _model;
}
public String getYear()
{
return _year;
}
//Setters
public void setMake(String make)
{
_make = make;
}
public void setModel(String model)
{
_model = model;
}
public void setYear(String year)
{
_year = year;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CarDetail extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
String[] myCars = {};
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> carAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, myCars);
setListAdapter(carAdapter);
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Login extends Activity implements OnClickListener{
private Button btnLogin;
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initializeVariables();
}
public void initializeVariables()
{
btnLogin = (Button) this.findViewById(R.id.bLogin);
etUsername = (EditText)this.findViewById(R.id.etUserName);
etPassword = (EditText)this.findViewById(R.id.etPassword);
btnLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
Log.i("Tag", "In Onclick Litener");
String uName = etUsername.getText().toString();
String pWord = etPassword.getText().toString();
if(uName.equals("owner") && pWord.equals("1234"))
{
Log.i("Tag", "username =" + uName + "Password =" + pWord);
Intent intent = new Intent(this, People.class);
startActivity(intent);
}
}
}
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Owner implements Parcelable {
private String _firstName;
private String _lastName;
private String _carId;
private Car _car;
public Owner()
{
this._firstName = "";
this._lastName = "";
this._carId = "";
}
public Owner(String lName)
{
this._lastName = lName;
}
public Owner(String lName, String cId)
{
this._lastName = lName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId, Car car)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
this._car = car;
}
//Getters
public String getFirstName()
{
return _firstName;
}
public String getLastName()
{
return _lastName;
}
public String getCarId()
{
return _carId;
}
public Car getCar()
{
return _car;
}
//Setters
public void setFirstName(String fName)
{
_firstName = fName;
}
public void setLastName(String lName)
{
_lastName = lName;
}
public void setCarId(String cId)
{
_carId = cId;
}
public void setCar(Car car)
{
_car = car;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(_firstName);
dest.writeString(_lastName);
dest.writeString(_carId);
dest.writeParcelable(_car, flags);
}
public Owner(Parcel source){
_firstName = source.readString();
_lastName = source.readString();
_carId = source.readString();
_car = source.readParcelable(Car.class.getClassLoader());
}
public class MyCreator implements Parcelable.Creator<Owner> {
public Owner createFromParcel(Parcel source) {
return new Owner(source);
}
public Owner[] newArray(int size) {
return new Owner[size];
}
}
}
package com.mb.carlovers;
import com.mb.carlovers.adapter.OwnerAdapter;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container, false);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Owner[] myOwners = null;
super.onCreate(savedInstanceState);
Bundle values = getActivity().getIntent().getExtras();
if(values != null)
{
myOwners = (Owner[]) values.getParcelableArray("test");
}
super.onActivityCreated(savedInstanceState);
ownerAdapter = new OwnerAdapter(getActivity(), R.layout.owner_detail , myOwners);
ownerAdapter.notifyDataSetChanged();
}
package com.mb.carlovers;
import java.util.List;
import com.mb.carlovers.asynctask.OnwerAsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class People extends FragmentActivity implements OnClickListener, OnItemSelectedListener {
private Button search;
private EditText etSearchBy, etSearchByID;
private Spinner spOption;
private String selectedOption = null;
private TextView tvErrorMessage;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.people);
InitializeVariables();
}
private void InitializeVariables()
{
etSearchBy = (EditText) this.findViewById(R.id.etByLastName);
etSearchByID = (EditText) this.findViewById(R.id.etCarID);
spOption = (Spinner) this.findViewById(R.id.spOption);
search = (Button) this.findViewById(R.id.bSearch);
search.setOnClickListener(this);
tvErrorMessage = (TextView) this.findViewById(R.id.tvErrorMessage);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.spOptions, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOption.setAdapter(adapter);
spOption.setOnItemSelectedListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
String searchByName = etSearchBy.getText().toString();
String searchById = etSearchByID.getText().toString();
if(selectedOption == null || selectedOption == "All")
{
if(searchByName.matches("") || searchById.matches(""))
{
tvErrorMessage.setText("You must select a last name and car id");
} else
{
}
} else if(selectedOption == "Name")
{
if(!searchByName.matches(""))
{
OnwerAsyncTask asynTask = new OnwerAsyncTask();
List<Owner> lt = null;
try {
lt = asynTask.execute("").get();
} catch (Exception e) {
e.printStackTrace();
}
Owner myOwners[] = lt.toArray(new Owner[lt.size()]);
Bundle data = new Bundle();
data.putParcelableArray("test", myOwners);
} else
{
tvErrorMessage.setText("You must enter the last name of the owner.");
}
} else if (selectedOption == "ID")
{
if(!searchById.matches(""))
{
String st = null;
String d = st;
} else
{
tvErrorMessage.setText("You must enter the car id that you'd like to search.");
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
switch(pos)
{
case 0:
selectedOption = "All";
break;
case 1:
selectedOption ="Name";
break;
case 2:
selectedOption ="ID";
break;
default:
selectedOption = null;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedOption ="ALL";
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Car;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CarAdapter extends ArrayAdapter<Car> {
private Context context;
private int layoutResourceId;
private Car data[] = null;
public CarAdapter(Context context, int resource, Car[] data) {
super(context, resource, data);
this.context = context;
this.layoutResourceId = resource;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CarHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CarHolder();
holder.tvMake = (TextView) row.findViewById(R.id.tvMake);
holder.tvModel = (TextView) row.findViewById(R.id.tvModel);
holder.tvYear = (TextView) row.findViewById(R.id.tvYear);
row.setTag(holder);
} else
{
holder = (CarHolder) row.getTag();
}
Car item = data[position];
holder.tvMake.setText(item.getMake().toString());
holder.tvModel.setText(item.getModel().toString());
holder.tvYear.setText(item.getYear().toString());
return row;
}
public static class CarHolder
{
TextView tvMake;
TextView tvModel;
TextView tvYear;
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Owner;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class OwnerAdapter extends ArrayAdapter<Owner> {
private Context context;
private int layoutResourceId;
private Owner data[] = null;
public OwnerAdapter(Context context, int textViewResourceId,Owner[] data) {
super(context, textViewResourceId, data);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OwnerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OwnerHolder();
holder.tvFName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCId = (TextView) row.findViewById(R.id.tvCarID);
row.setTag(holder);
} else
{
holder = (OwnerHolder) row.getTag();
}
Owner item = data[position];
holder.tvFName.setText(item.getFirstName());
holder.tvLName.setText("Example");
holder.tvCId.setText("1");
return row;
}
static class OwnerHolder
{
TextView tvFName;
TextView tvLName;
TextView tvCId;
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Car;
import android.os.AsyncTask;
public class CarAsyncTask extends AsyncTask<String, Void, List<Car>> {
private List<Car> item = null;
#Override
protected List<Car> doInBackground(String... params) {
item = new ArrayList<Car>();
item.add(new Car("Chevy","Caprice","2002"));
item.add(new Car("Chevy","Malibu","2014"));
item.add(new Car("Dodge","Stratus","2002"));
item.add(new Car("Saturn","L300","2004"));
return item;
}
#Override
protected void onPostExecute(List<Car> result) {
super.onPostExecute(result);
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Owner;
import android.os.AsyncTask;
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
#Override
protected List<Owner> doInBackground(String... params) {
try
{
items = new ArrayList<Owner>();
Owner own = new Owner();
own.setFirstName("John");
own.setLastName("Smith");
own.setCarId("1");
items.add(own);
Owner own1 = new Owner();
own1.setFirstName("Samantha");
own1.setLastName("Right");
own1.setCarId("2");
items.add(own1);
Owner own2 = new Owner();
own2.setFirstName("Regie");
own2.setLastName("Miller");
own2.setCarId("3");
items.add(own2);
Owner own3 = new Owner();
own3.setFirstName("Mark");
own3.setLastName("Adam");
own3.setCarId("4");
items.add(own3);
} catch(Exception ex)
{
ex.toString();
}
return items;
}
#Override
protected void onPostExecute(List<Owner> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
// car_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Car Detail Page" />
</LinearLayout>
// car_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvMake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvModel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
//customize_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No record to be displayed."
/>
</LinearLayout>
//Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Login" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etUserName"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
>
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etPassword"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:inputType="textPassword" />
<Button
android:id="#+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:text="Login" />
</LinearLayout>
//owner_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvCarID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
// People.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by last name"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
/>
<EditText
android:id="#+id/etByLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by car id"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<EditText
android:id="#+id/etCarID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<Spinner
android:id="#+id/spOption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/spOptions"
/>
<TextView
android:id="#+id/tvErrorMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:layout_marginTop="10dp"
android:text="" />
<Button
android:id="#+id/bSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="2"
>
<fragment
android:id="#+id/fOwnerDetail"
android:name="com.mb.carlovers.OwnerDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<fragment
android:id="#+id/fragment1"
android:name="com.mb.carlovers.CarDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
/>
</LinearLayout>
</LinearLayout>
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(ownerAdapter);
}
}
Your code has a lot of problems:
1 Never call lifecycle methods on your own like you do in the OwnerDetail class with super.onActivityCreated(savedInstanceState);
2 Bundle values = getActivity().getIntent().getExtras(); ... values.getParcelableArray("test"); will normally fail because this piece of code will get the activity reference, get the Intent that started the activity and then try to find data passed in under the test key in that Intent. You don't pass such data to the People activity so there will be nothing to be found. You'd normally want to pass a Bundle containing the data at the moment of the creation of the fragment.
3 If you use the fragment in the xml layout you'll not be able to use a Bundle to pass data, instead you either add the fragment manually with transactions and then use a Bundle or you create a setter method in the fragment class and use that. So instead of Bundle data = new Bundle(); data.putParcelableArray("test", myOwners);, which does nothing, get a reference to your fragment and pass the myOwners array through a method.
4 Your AsyncTask will be pretty useless if you use them with .get() because the get() method will wait the AsyncTask to finish, blocking the UI tread as well. Instead you should just start the AsyncTask and then in the onPostExecute() pass the data around.
Here is an example with a simple method which will not change most of your code(which will happen if you manually add the fragments):
// where you start the owner asynctask
if(!searchByName.matches("")) {
OnwerAsyncTask asynTask = new OnwerAsyncTask(People.this);
asynTask.execute("");
}
//...
Then change the OnwerAsyncTask like this:
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
private FragmentActivity mActivity;
public OnwerAsyncTask(FragmentActivity activity) {
mActivity = activity;
}
// doInBackground()...
#Override
protected void onPostExecute(List<Owner> result) {
//I'm assuming that items is the data you want to return, so
// find the OwnerDetail fragment and directly assign the data
OwnerDetail fragment = (OwnerDetail)mActivity.getSupportFragmentManager().findFragmentById(R.id.fOwnerDetail);
fragment.setData(); // to setData you'll pass the data you have in the AsyncTask
// the items list? or you transform that into an array?
}
and in the OwnerDetail fragment:
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
public void setData() {
// update the adapter, create a new one etc.
}
i am trying to create a listview in my android application. But i am getting Resource Not found Exception while running the project.
activity_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<include
android:id="#+id/title_bar"
layout="#layout/title_bar" />
<ListView
android:id="#+id/FeedList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title_bar"
></ListView>
</RelativeLayout>
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF">
<ImageButton
android:id="#+id/FeedType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#E0E0E0"
android:padding="9dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/FeedTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Feed Title"
android:textSize="18sp"
android:layout_toRightOf="#+id/FeedType"
android:paddingLeft="5dp"
android:textColor="#000000"
/>
<TextView
android:id="#+id/FeedPostedBy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/FeedTitle"
android:text="by FeedOwner"
android:layout_toRightOf="#+id/FeedType"
android:paddingLeft="5dp"
android:textSize="10sp"
/>
<TextView
android:id="#+id/FeedContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/FeedPostedBy"
android:layout_toRightOf="#+id/FeedType"
android:paddingLeft="5dp"
android:paddingTop="8dp"
android:text="The content posted as a feed by the feed owner will appear here"
android:textSize="10sp"/>
</RelativeLayout>
ListAdapter Class :
package com.tcs.internal.prime;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter{
private Activity listAdapterActivity = null;
private ArrayList<HashMap<String,String>> data;
private static LayoutInflater inflater;
public ListAdapter(Activity ListActivity,ArrayList<HashMap<String, String>> listData)
{
listAdapterActivity = ListActivity;
data = listData;
inflater = (LayoutInflater)listAdapterActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View listItem = convertView;
if(listItem == null)
listItem = inflater.inflate(R.id.FeedList, null);
ImageButton feedIcon = (ImageButton) listItem.findViewById(R.id.FeedType);
TextView feedTitle = (TextView) listItem.findViewById(R.id.FeedTitle);
TextView feedOwner = (TextView) listItem.findViewById(R.id.FeedPostedBy);
TextView feedContent = (TextView) listItem.findViewById(R.id.FeedContent);
HashMap<String, String> feedData = new HashMap<String, String>();
feedData = data.get(position);
feedIcon.setImageResource(R.drawable.ic_launcher);
feedTitle.setText(feedData.get("FeedTitle"));
feedOwner.setText(feedData.get("FeedOwner"));
feedContent.setText(feedData.get("FeedContent"));
return listItem;
}
}
MainActivity class :
package com.tcs.internal.prime;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> data = new HashMap<String, String>();
data.put("FeedTitle","Application crashed when launched in Windows 7");
data.put("FeedOwner", "By Venkatramanan");
data.put("FeedContent","Launch the financial aid adminstration in windows 7 environment");
feedList.add(data);
data.clear();
data.put("FeedTitle","Application crashed when launched in Windows 8 ");
data.put("FeedOwner", "By Siva Guru");
data.put("FeedContent","Launch the financial aid adminstration in windows 8 environment");
feedList.add(data);
ListView feedListView = (ListView)findViewById(R.id.FeedList);
ListAdapter listAdapter = new ListAdapter(this, feedList);
feedListView.setAdapter(listAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I am getting this following exception :
android.content.res.Resources$NotFoundException: Resource ID #0x7f070001 type #0x12 is not valid
All you have to inflate the custom layout in your listview's adapter's getview method as
listItem = inflater.inflate(R.layout.list_item, null);
instead of
listItem = inflater.inflate(R.id.FeedList, null);