Nitez Nitez - 10 days ago 6
Android Question

populate listview from database in fragment

I want to populate the listview from database in SocialFragment.java. I have done as below and shows error- incompatible types:SocialFragment cannot be converted to Context. Please help me to populate listview from databse in a Fragment.

SocialFragment.java

package layout;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.example.kiran.herau.Help;
import com.example.kiran.herau.NewDatabaseAdapter;
import com.example.kiran.herau.R;
import com.example.kiran.herau.VivzDatabaseAdapter;


public class SocialFragment extends Fragment {

protected BaseAdapter mAdapter;
private SimpleCursorAdapter dataAdapter;
NewDatabaseAdapter vivzHelper;
TextView text;

@Nullable

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.social_layout,null);
displayListView(view);
return view;
}

private void displayListView(View view) {

vivzHelper = new NewDatabaseAdapter(this);
Cursor cursor = vivzHelper.fetchAllData();

// The desired columns to be bound
String[] columns = new String[] {

NewDatabaseAdapter.NewDatabaseHelper.UID,
NewDatabaseAdapter.NewDatabaseHelper.NAME,
NewDatabaseAdapter.NewDatabaseHelper.ADDRESS,

};

// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.id,
R.id.name,
R.id.address,
};

// create the adapter using the cursor pointing to the desired data
//as well as the layout information

dataAdapter = new SimpleCursorAdapter(
this, R.layout.routinerow,
cursor,
columns,
to,
0);

ListView listView = (ListView) view.findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);

}
}

Answer

You need to replace

vivzHelper = new NewDatabaseAdapter(this);

with:

vivzHelper = new NewDatabaseAdapter(getActivity());

And you need to replace:

dataAdapter = new SimpleCursorAdapter(
            this, R.layout.routinerow,
            cursor,
            columns,
            to,
            0);

with:

dataAdapter = new SimpleCursorAdapter(
            getActivity(), R.layout.routinerow,
            cursor,
            columns,
            to,
            0);

This should help you out, hopefully :)

Comments