How to Seed DB after DontDropDbJustCreateTablesIfModelChanged - entity-framework-4.1

Recently I've had my DB rights reduced so that I can't drop and recreate databases. This has led to me using the DontDropDbJustCreateTablesIfModelChanged Database initialisation from nuget.
However I'm now stuck as to how I should seed data as the Seed function is not in the initialisation so I can't override it. This is what I'd like to be able to do.
public class MyDBInitialiser : DontDropDbJustCreateTablesIfModelChanged<MyContext>
{
protected override void Seed(MyContext context)
{
base.Seed(context);
context.Item.Add(new Item() { ItemId = 1, Name = "Item 1"});
context.Item.Add(new Item() { ItemId = 2, Name = "Item 2"});
context.Item.Add(new Item() { ItemId = 3, Name = "Item 3"});
}
}
Is there another way of seeding data in this situation.

Simply,
public class DontDropDbJustCreateTablesIfModelChanged<T>
: IDatabaseInitializer<T> where T : DbContext
{
private EdmMetadata _edmMetaData;
public void InitializeDatabase(T context)
{
ObjectContext objectContext =
((IObjectContextAdapter)context).ObjectContext;
string modelHash = GetModelHash(objectContext);
if (CompatibleWithModel(modelHash, context, objectContext))
return;
DeleteExistingTables(objectContext);
CreateTables(objectContext);
SaveModelHashToDatabase(context, modelHash, objectContext);
Seed(context);
}
protected virtual void Seed(T context) { }
private void SaveModelHashToDatabase(T context, string modelHash,
ObjectContext objectContext)
{
if (_edmMetaData != null) objectContext.Detach(_edmMetaData);
_edmMetaData = new EdmMetadata();
context.Set<EdmMetadata>().Add(_edmMetaData);
_edmMetaData.ModelHash = modelHash;
context.SaveChanges();
}
private void CreateTables(ObjectContext objectContext)
{
string dataBaseCreateScript =
objectContext.CreateDatabaseScript();
objectContext.ExecuteStoreCommand(dataBaseCreateScript);
}
private void DeleteExistingTables(ObjectContext objectContext)
{
objectContext.ExecuteStoreCommand(Dropallconstraintsscript);
objectContext.ExecuteStoreCommand(Deletealltablesscript);
}
private string GetModelHash(ObjectContext context)
{
var csdlXmlString = GetCsdlXmlString(context).ToString();
return ComputeSha256Hash(csdlXmlString);
}
private bool CompatibleWithModel(string modelHash, DbContext context,
ObjectContext objectContext)
{
var isEdmMetaDataInStore =
objectContext.ExecuteStoreQuery<int>(LookupEdmMetaDataTable)
.FirstOrDefault();
if (isEdmMetaDataInStore == 1)
{
_edmMetaData = context.Set<EdmMetadata>().FirstOrDefault();
if (_edmMetaData != null)
{
return modelHash == _edmMetaData.ModelHash;
}
}
return false;
}
private string GetCsdlXmlString(ObjectContext context)
{
if (context != null)
{
var entityContainerList = context.MetadataWorkspace
.GetItems<EntityContainer>(DataSpace.SSpace);
if (entityContainerList != null)
{
var entityContainer = entityContainerList.FirstOrDefault();
var generator =
new EntityModelSchemaGenerator(entityContainer);
var stringBuilder = new StringBuilder();
var xmlWRiter = XmlWriter.Create(stringBuilder);
generator.GenerateMetadata();
generator.WriteModelSchema(xmlWRiter);
xmlWRiter.Flush();
return stringBuilder.ToString();
}
}
return string.Empty;
}
private static string ComputeSha256Hash(string input)
{
byte[] buffer = new SHA256Managed()
.ComputeHash(Encoding.ASCII.GetBytes(input));
var builder = new StringBuilder(buffer.Length * 2);
foreach (byte num in buffer)
{
builder.Append(num.ToString("X2",
CultureInfo.InvariantCulture));
}
return builder.ToString();
}
private const string Dropallconstraintsscript =
#"select
'ALTER TABLE ' + so.table_name + ' DROP CONSTRAINT '
+ so.constraint_name
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS so";
private const string Deletealltablesscript =
#"declare #cmd varchar(4000)
declare cmds cursor for
Select
'drop table [' + Table_Name + ']'
From
INFORMATION_SCHEMA.TABLES
open cmds
while 1=1
begin
fetch cmds into #cmd
if ##fetch_status != 0 break
print #cmd
exec(#cmd)
end
close cmds
deallocate cmds";
private const string LookupEdmMetaDataTable =
#"Select COUNT(*)
FROM INFORMATION_SCHEMA.TABLES T
Where T.TABLE_NAME = 'EdmMetaData'";
}
&
public class Population : DontDropDbJustCreateTablesIfModelChanged</* DbContext */>
{
protected override void Seed(Syndication Context)
{
/* Seeding :) */
}
}
&
Database.SetInitializer</* DbContext */>(new Population());

I my projects I split the db initialization from the db seeding. If you use inversion of control, you should be able to do something like this in your composition root (Application_Start if you are consuming the DbContext from a web app):
var seeder = ServiceLocatorPattern
.ServiceProviderLocator.Current.GetService<ISeedDb>();
if (seeder != null) seeder.Seed();
The interface:
public interface ISeedDb, IDisposable
{
void Seed();
}
A possible implementation:
public class MyDbSeeder : ISeedDb
{
private readonly MyContext _context;
public MyDbSeeder(MyContext context)
{
_context = context;
}
public void Seed()
{
_context.Item.Add(new Item { ItemId = 1, Name = "Item 1" });
// ... etc
}
public void Dispose()
{
_context.Dispose();
}
}

Related

Error parsing data JSON, Fragment Android Studio

Someone please help me why my result always error parsing data ?
My app run smoothly but does not display anything. i feel so stuck here.
this is my code
Sorry for bad english
API JSON
public function getkategori2(){
$data = array();
$token = $this->input->post('f_token');
$tabel = $this->input->post('f_tabel');
if ($token == '' || $tabel == ''){
$data['result'] = false;
$data['msg'] = "Data Kosong";
echo json_encode($data);
return;
}
$sql = 'SELECT * FROM '.$tabel.'_kategori INNER JOIN files WHERE '.$tabel.'_kategori.id_kategori = files.id_kategori';
$q = $this->db->query($sql);
if ($q->num_rows()>0) {
foreach ($q->result() as $value) {
$kategori = array(
'nama_kategori' => $value->nama_kategori,
'file_name' => $value->file_name,
);
};
$data['result'] = true;
$data['kategori_data'] = $kategori;
$data['msg'] = '';
} else {
$data['result'] = false;
$data['msg'] = 'error';
}
echo json_encode($data);
}
JSON Result
{
"result":true,
"kategori_data":
{
"nama_kategori":"Pasta",
"file_name":"1_Pasta.jpg"
},
"msg":""
}
KategoriAdapter
public class KategoriAdapter extends RecyclerView.Adapter<KategoriAdapter.ViewHolder> {
private ArrayList<Kategori> mData;
private Context context;
private SessionManager sesi;
public KategoriAdapter (Context context, ArrayList<Kategori> mData){
this.context = context;
this.mData = mData;
}
#Override
public KategoriAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(context)
.inflate(R.layout.item_list_kategori, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(KategoriAdapter.ViewHolder holder, int position) {
Kategori k = mData.get(position);
String kategori = k.getKategoriNama();
String gambar = k.getImg();
//masukan kedalam object viewholder
holder.tvKategori.setText(kategori);
Picasso.with(context)
.load(Constant.BASE_IMAGE + sesi.getTabel() + "/kategori/" + gambar)
.into(holder.ivKategori);
}
//buta object interface onAdapterjabatanListener
private OnAdapterListener listener;
//buat method untuk mendefiniskan listenernya
public void setListener(OnAdapterListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return mData == null ? 0 : mData.size();
}
//buat class yang extend dari ViewHolder
class ViewHolder extends RecyclerView.ViewHolder{
public LinearLayout container;
public TextView tvKategori;
public ImageView ivKategori;
public ViewHolder(View v){
super(v);
//baru hubungkan variablenya dengan item yang ada di class layout item
container = v.findViewById(R.id.container);
tvKategori = v.findViewById(R.id.tvKategori);
ivKategori = v.findViewById(R.id.ivKategori);
}
}
KategoriFragment
public class KategoriFragment extends Fragment {
SessionManager sesi;
private ArrayList<Kategori> data;
private OkHttpClient okClient;
private RecyclerView rvData;
public KategoriFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_kategori, container, false);
sesi = new SessionManager(getActivity());
data = new ArrayList<>();
okClient = new OkHttpClient();
rvData = rootView.findViewById(R.id.rvData);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
rvData.setLayoutManager(manager);
getData();
return rootView;
}
private void getData(){
data.clear();
String url = Constant.BASE_URL + "getkategori2";
FormBody parameters = new FormBody.Builder()
.add("f_token", sesi.getToken())
.add("f_tabel", sesi.getTabel())
.build();
//buat request untuk ambil data
Request request = new Request.Builder()
.url(url)
.post(parameters)
.build();
okClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
e.printStackTrace();
RbHelpers.pesan(getActivity(),
"error :" + e.getMessage());
}
});
}
#Override
public void onResponse(Call call,final Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//hilangkan dialognya
}});
final String responData = response.body().string();
RbHelpers.pre("respon data : " + responData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//debug hasilnya kedalam android monitor
try {
//parsing json
try {
JSONObject json = new JSONObject(responData);
Log.d("tagJSON",json.toString());
//check hasilnya apakah true or false
boolean hasil = json.getBoolean("result");
if (hasil){
//ada datanya
//buat object jsonArray
JSONArray jArray = json.getJSONArray("kategori_data");
//looping data dan masukkan kedalam arraylist
for (int i = 0; i < jArray.length(); i++){
JSONObject jObj = jArray.getJSONObject(i);
Kategori kategori = new Kategori();
kategori.setKategoriNama(jObj.getString("nama_kategori"));
kategori.setImg(jObj.getString("file_name"));
//tinggal masukan ke arraylist
data.add(kategori);
}
} else {
String msg = json.getString("msg");
RbHelpers.pesan(getActivity(), msg);
}
//tinggal masukin ke recylerview
//UserAdapter adapter = new UserAdapter
KategoriAdapter adapter = new KategoriAdapter(getActivity(), data);
rvData.setAdapter(adapter);
} catch (JSONException e){
RbHelpers.pesan(getActivity(), "Error parsing data");
e.printStackTrace();
}
} catch (Exception e) {
RbHelpers.pesan(getActivity(), "Error ambil data");
e.printStackTrace();
}
}
});
}
});
}
Think this is the wrong part "kategori_data" is a JSONObject , not a JSONArray, Check the correct format in jsonBlob as
Here you have an example of a mine working project where i have a model Articulo(Product) and I make a request to retrieve that object data
try{
// Get the JSON array
JSONObject result = response.getJSONObject("articulo");
int i ;
for(i=0;i<1;i++){
JSONObject articulo = result;
ListaArticulos item = new ListaArticulos(
articulo.getString("IdArticulo"),
articulo.getString("Precio"),
articulo.getString("Stock"),
articulo.getString("Consultas"),
articulo.getString("IdCategoria"),
articulo.getString("Descripcion"),
articulo.getString("Observacion"),
articulo.getString("Codigo"),
articulo.getString("Imagen")
);
So in conclusion what you need to do is change JSONArray jArray = json.getJSONArray("kategori_data");
for
JSONObject jsonOb = json.getJSONObject("kategori_data");

Modify Existing alarms AWS

I want to know how do i read and modify all the alarms ? I am currently facing problem to read the next set of alarms. The first set contains first 50.
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
DescribeAlarmsResult alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
System.out.println(alarmsResult.getMetricAlarms().size());
System.out.println(alarmsResult.getNextToken());
DescribeAlarmsRequest describeAlarmsRequest1 = new DescribeAlarmsRequest();
describeAlarmsRequest1.setNextToken(alarmsResult.getNextToken());
DescribeAlarmsResult alarmsResult1 = cloudWatch.describeAlarms(describeAlarmsRequest1);
System.out.println(alarmsResult1.getMetricAlarms().size());
I did it the following way and it worked.
public class Alarms {
private static AmazonCloudWatchClient cloudWatch;
private static AmazonSNSClient client;
private static ClientConfiguration clientConfiguration;
private static final String AWS_KEY = "";
private static final String AWS_SECRET_KEY = "";
static {
BasicAWSCredentials credentials = new BasicAWSCredentials(AWS_KEY,AWS_SECRET_KEY);
cloudWatch = new AmazonCloudWatchClient(credentials);
clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeout(10000);
clientConfiguration.setSocketTimeout(30000);
clientConfiguration.setMaxErrorRetry(5);
client = new AmazonSNSClient(credentials, clientConfiguration);
}
public static void main(String args[]) {
cloudWatch.setEndpoint("monitoring.us-east-1.amazonaws.com");
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
//describeAlarmsRequest.setStateValue(StateValue.OK);
DescribeAlarmsResult alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
List<MetricAlarm> metricAlarmList = new ArrayList<>();
metricAlarmList.addAll(alarmsResult.getMetricAlarms());
do {
describeAlarmsRequest.withNextToken(alarmsResult.getNextToken());
alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
metricAlarmList.addAll(alarmsResult.getMetricAlarms());
} while (alarmsResult.getNextToken() != null);
int i = metricAlarmList.size();
System.out.println("size " + i);
for(MetricAlarm alarm : metricAlarmList){
System.out.println(i--);
modifyalarm(alarm);
}
}
private static void modifyalarm(MetricAlarm alarm) {
Dimension instanceDimension = new Dimension();
instanceDimension.setName("InstanceId");
instanceDimension.setValue(alarm.getAlarmName());
PutMetricAlarmRequest request = new PutMetricAlarmRequest()
.withActionsEnabled(true).withAlarmName(alarm.getAlarmName())
.withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold)
.withDimensions(Arrays.asList(instanceDimension))
.withAlarmActions(getTopicARN())
.withEvaluationPeriods(5)
.withPeriod(60)
.withThreshold(5.0D)
.withStatistic(Statistic.Average)
.withMetricName("StatusCheckFailed")
.withNamespace("AWS/EC2");
cloudWatch.putMetricAlarm(request);
}
private static String getTopicARN() {
ListTopicsResult listTopicsResult = client.listTopics();
String nextToken = listTopicsResult.getNextToken();
List<Topic> topics = listTopicsResult.getTopics();
String topicARN = "";
while (nextToken != null) {
listTopicsResult = client.listTopics(nextToken);
nextToken = listTopicsResult.getNextToken();
topics.addAll(listTopicsResult.getTopics());
}
for (Topic topic : topics) {
if (topic.getTopicArn().contains("status-alarms")) {
topicARN = topic.getTopicArn();
break;
}
}
return topicARN;
}
}

I want to create highchart widget by Eclipse RAP and i follow "RAP/Custom Widgets FAQ",but there is error?

i want to create some highchart widget by Eclipse RAP ,and i follow the official guide like this
handlejs:
var CKEDITOR_BASEPATH = "rwt-resources/";
(function(){
'use strict';
rap.registerTypeHandler( "rap.sunline.HighCharts", {
factory : function( properties ) {
var parent = rap.getObject( properties.parent );
// var element = document.createElement( "div" );
// parent.append( element );
// $(element).html("askldfjaskljdk");
return {};
}
});
}());
widget.java:
public class HightChartComposite extends Composite {
private static final String RESOURCES_PATH = "resources/";
private static final String REGISTER_PATH = "hightcharts/";
private static final String[] RESOURCE_FILES = { "jquery-2.1.0.min.js", "highcharts.js","ChartPaintListener.js" };
private static final String REMOTE_TYPE = "rap.sunline.HightCharts";
private final RemoteObject remoteObject;
private final OperationHandler operationHandler = new AbstractOperationHandler() {
#Override
public void handleSet(JsonObject properties) {
// JsonValue textValue = properties.get("text");
// if (textValue != null) {
// text = textValue.asString();
// }
}
};
public HightChartComposite(Composite parent, int style) {
super(parent, style);
registerResources();
loadJavaScript();
Connection connection = RWT.getUISession().getConnection();
remoteObject = connection.createRemoteObject(REMOTE_TYPE);
remoteObject.setHandler(operationHandler);
remoteObject.set("parent", WidgetUtil.getId(this));
}
private void registerResources() {
ResourceManager resourceManager = RWT.getResourceManager();
boolean isRegistered = resourceManager.isRegistered(REGISTER_PATH + RESOURCE_FILES[0]);
if (!isRegistered) {
try {
for (String fileName : RESOURCE_FILES) {
register(resourceManager, fileName);
}
} catch (IOException ioe) {
throw new IllegalArgumentException("Failed to load resources", ioe);
}
}
}
private void loadJavaScript() {
JavaScriptLoader jsLoader = RWT.getClient().getService(JavaScriptLoader.class);
ResourceManager resourceManager = RWT.getResourceManager();
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "jquery-2.1.0.min.js"));
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "highcharts.js"));
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "ChartPaintListener.js"));
}
private void register(ResourceManager resourceManager, String fileName) throws IOException {
ClassLoader classLoader = HightChartComposite.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(RESOURCES_PATH + fileName);
try {
resourceManager.register(REGISTER_PATH + fileName, inputStream);
} finally {
inputStream.close();
}
}
// //////////////////
// overwrite methods
#Override
public void setLayout(Layout layout) {
throw new UnsupportedOperationException("Cannot change internal layout of CkEditor");
}
}
the error is occur:
Uncaught Error: Operation "create" on target "r6" of type "null" failed:
No Handler for type rap.sunline.HightCharts
Properties:
parent = w5
and i have a question about this , what differents from extends Canvas and Composite;
You forget to implement setters in your javascript code.
The created object is stored by the framework under its object id. This object has to implement setter methods that match the properties defined in the handler, which will then be called when the server sends a set operation for a given property.

Json rpc claculator

My main activity: I have created threads and handler and tried calling it to establish a connection to a particular server:
public void mResult (){
Double secondNum = Double.parseDouble(screenView.getText().toString());
Double result = 0.0;
this.result=result;
// thread call
android.os.Handler aHandler = new android.os.Handler();
DoCalc myCalc = new DoCalc(aHandler, firstNum, secondNum, Operation);
myCalc.start();
screenView.setText(String.valueOf(result));
}
my main thread
class DoCalc extends Thread {
private android.os.Handler handler;
private double left,right;
private String oper;
public DoCalc(android.os.Handler myHandle, double left, double right, String oper){
this.handler = myHandle;
this.left = left;
this.right = right;
this.oper = oper;
}
public DoCalc(Handler aHandler, Double firstNum, Double secondNum, String operation){
this.handler = aHandler;
this.left = firstNum;
this.right = secondNum;
this.oper = operation;
}
public void run(){
Double result = 0.0;
String url = "http://129.219.151.99:8080/JsonRPC/calc";
try{
HttpJsonRpcClientTransport transport =
new HttpJsonRpcClientTransport(new URL(url));
transport.call(url);
LoggingPermission JsonRpcInvoker;
org.json.rpc.client.JsonRpcInvoker invoker = new JsonRpcInvoker();
Calculator calc = invoker.get(transport, "calc", Calculator.class);
if(oper.equals("+")){
result = calc.add(left,right);
}
if(oper.equals("-")){
result = calc.subtract(left, right);
}
if(oper.equals("*")){
result = calc.multiply(left, right);
}
if(oper.equals("/")){
result = calc.divide(left, right);
}
//FinalResult set = new FinalResult(result);
handler.post(new FinalResult(result));
// set.start();
}catch (Exception ex){
android.util.Log.w("calc","exception in call: "+ex.getMessage());
}
}
class FinalResult extends Thread implements Runnable {
double result;
EditText screenView;
public FinalResult(double result){
this.result = result;
}
public void run(){
android.util.Log.w("calc","result is: "+result);
System.out.println("result is"+result);
screenView.setText(String.valueOf(result));
}
}
}
}
I think my json rpc is not working am just getting 0.0 when ever I do any calculation

How to create my own arrayAdapter for listView - Android [duplicate]

This question already has answers here:
BaseAdapter class wont setAdapter inside Asynctask - Android
(4 answers)
Closed 9 years ago.
I am trying to create my own arrayAdapter so I can place multiple textviews inside of a listview. I have searched everywhere and can not find a way to do it. I am new to this and not so sure how to handle it. So far I have an asynctask that gathers 3 strings in a JSON method. These strings are what I want placed in the textViews but I have no idea how to do so, here is my current code.
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
private ArrayAdapter<String> mAdapter = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
final String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
ArrayList<String> myList = new ArrayList<String>();
class MyClassAdapter extends ArrayAdapter<String> {
private Context context;
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<String> items) {
super(context, textViewResourceId, items);
this.context = context;
}
public View getView(int position, View convertView) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
String item = getItem(position);
if (item!= null) {
// My layout has only one TextView
TextView commentView = (TextView) view.findViewById(R.id.listComment);
TextView usernameView = (TextView) view.findViewById(R.id.listPostedBy);
TextView NumberView = (TextView) view.findViewById(R.id.listNumber);
// do whatever you want with your string and long
commentView.setText(comments);
NumberView.setText(numbers);
usernameView.setText(usernames);
}
return view;
}
}
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
}
}
new loadComments().execute();
This code does not work but I think I am on the right track.
Let us say, you create a class that hold your information about the comments instead of creating three related Arrays :
class Commentary
{
public String username;
public String comment;
public int commentaryIndex;
}
The BaseAdapter can take a List as a parameter whereas the ArrayAdapter wouldn't.
class MyRealAdapter extends BaseAdapter
{
private List<Commentary> comments;
public MyRealAdapter(List<Commentary> comments )
{
this.comments = comments;
}
#Override
public int getCount() {
return comments.size();
}
#Override
public Object getItem(int index) {
return comments.get(index);
}
#Override
public long getItemId(int index) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Commentary c = (Commentary) getItem(position);
//c.username, c.comment, c.commentaryIndex
// create the view and stuff
return null;
}
}
As you can see, you again have the getView method but now you can retrieve your complete objet and not just a String.
There is a couple more method to override, but as you can see it's very simple.
You might need to pass other argument like a Context or a LayoutInflater to the constructor, but it's not mandatory.
EDIt :
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
ArrayList<Commentary> comments = new ArrayList<commentary>();
for ( int i=0; i<commentArray.length(); i++ ) {
Commentary c = new Commentary();
c.username = usernameArray.getString(i);
c.comment = commentArray.getString(i);
c.commentaryIndex = Integer.parseInt(numberArray.getString(i));
comments.add(c);
}
MyRealAdapter adapter = new MyRealAdapter(comments);