Android How to save msg into local storage? - android

I'm pretty new to the Android developer. I'm currently making an simple message app. so i want to store all the text message I received from node server. I don't really now how should i do this.
the msg I received from node server is JSONObject like:
{"name":"XX", "id":"XX","message":"xxxxxxxx"}
and I'm using a Custom ArrayAdepter to display the text:
public class ChatArrayAdapter extends ArrayAdapter<Text> {
private TextView text,avatar;
private List<Text> msgcontx = new ArrayList<Text>();
private LinearLayout wrapper;
#Override
public void add(Textobject){
msgcontx.add(object);
super.add(object);
}
public ChatArrayAdapter(Context context,int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount(){
return this.msgcontx.size();
}
public Text getItem(int index){
return this.msgcontx.get(index);
}
public View getView(int position,View convertView,ViewGroup parent){
View row = convertView;
if(row == null){
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chat_listview, parent,false);
}
wrapper = (LinearLayout)row.findViewById(R.id.wrapper);
Text comment = getItem(position);
avatar = (TextView)row.findViewById(R.id.avatar);
avatar.setText(comment.userID);
avatar.setVisibility(comment.left? View.VISIBLE: View.GONE);
text = (TextView)row.findViewById(R.id.comment);
text.setText(comment.comment);
// chat background to be changed
text.setBackgroundResource(comment.left ? R.drawable.bg_chat_recipient : R.drawable.bg_chat_sender );
wrapper.setGravity(comment.left? Gravity.START : Gravity.END);
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte){
return BitmapFactory.decodeByteArray(decodedByte, 0,decodedByte.length );
}
}
now I don't know how should I store those msg I received from node server at local storage, and when i open the app, I want to also display the msg history.
should I use SQL? but how should I store the msg? put them in different rows?
I know it might be a dumb question, But I really don't know how to store the msg to local storage and read them again.
Anyone can give a brief introduction? Thanks a lot!

You should use some kind of database.I recommend an sql db with an orm - it lets you create a database based on classes and eliminates the need in ton of sql.
I like active android, but also take a look at sugar orm.
You should have a messages table, and each row in the table will be a message.In an orm you define the message using a class. example code (using ActiveAndroid orm):
#Table(name="Messages")
class Message extends Model {
String name;
String id;
String message;
//the empty consructor is required by active android
public Message(){
super();
}
}
to actually enter the messages into the databse you will need to parse the json and create Messages objects from them, then save them.To parse the json into the Message object you can use Gson or logan square.

Related

Can't save multiple custom objects in SharedPreferences?

Here is my issue. I can save an object, but if I save another object, it will erase the previous item. I'm using gson lib to save my items. After some researches I've seen this How to use SharedPreferences to save more than one values?
But I can't use it because of my custom objects, if I use .toString(), I will not be able to get back my original item. I know that's it's the same key used to save object that will erase the previous one but I dont really know how to give a different key every time I will save an item.
Code to add :
addFav.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (currentProduit.getIsAdded() ==0) {
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String myJson = gson.toJson(currentProduit);
Log.i("INFO", "Value of saved data" + myJson);
prefsEditor.putString("myproduct", myJson);
prefsEditor.apply();
Toast.makeText(getApplicationContext(), "Data saved !", Toast.LENGTH_SHORT).show();
addFav.setText(R.string.delete_fav);
currentProduit.setIsAdded(1);
} else {
addFav.setText(R.string.add_fav);
currentProduit.setIsAdded(0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.remove("myproduct").apply();
Toast.makeText(getApplicationContext(), "Data removed !", Toast.LENGTH_SHORT).show();
}
}
});
Code to get back from other activity:
String myJson = mPrefs.getString("myproduct", "");
Log.i("INFO", "Value of loaded data" + myJson);
if (myJson.isEmpty() && favProductList.isEmpty()) {
listview_R.setAdapter(null);
Log.i("INFO", "No items");
title.setText(getString(R.string.fav));
} else if (myJson.isEmpty() && favProductList != null) {
myCustomAdapterVersionR = new CustomAdapter_VersionR(getApplicationContext(), favProductList);
listview_R.setAdapter(myCustomAdapterVersionR);
} else {
Product savedProduct = gson.fromJson(myJson, Product.class);
favProductList.add(savedProduct);
Log.i("INFO", "Favorite was added");
myCustomAdapterVersionR = new CustomAdapter_VersionR(getApplicationContext(), favProductList);
listview_R.setAdapter(myCustomAdapterVersionR);
}
Thanks for helping ! Btw, since it's not saving a lot of items, I didnt use sqlite db, cheers !
EDIT: I tried Juan Cortés solution, but I have this error after getting back the shared preferences --> error: incompatible types: CustomProduct[] cannot be converted to List, here is the code
if (fromPrefs.isEmpty() && favProductList.isEmpty()) {
listview_R.setAdapter(null);
Log.i("INFO", "No items");
title.setText(getString(R.string.fav));
} else {
//Product savedProduct = gson.fromJson(fromPrefs, Product.class);
//favProductList.add(savedProduct);
//Get the Object array back from the String `fromPrefs`
CustomProduct[] reInflated = gson.fromJson(fromPrefs,CustomProduct[].class);
Log.i("INFO", "Favorite was added");
myCustomAdapterVersionR = new CustomAdapter_VersionR(getApplicationContext(), reInflated); //error
listview_R.setAdapter(myCustomAdapterVersionR);
}
Thanks !
As an overly simplified app for example, you could define a custom class as follows (of course you'll have to adapt it to your particulars). The concept is create an array of custom objects, convert it to json, store it. It's really straightforward once you see it.
The code
Gson gson = new Gson();
//Create an array to work with it, dummy content
CustomProduct[] exampleList = new CustomProduct[10];
for(int i=0;i<10;i++){
exampleList[i] = new CustomProduct("string","number:"+i);
}
//Get a String representation of the objects
String forStoring = gson.toJson(exampleList);
//HERE you can store and retrieve to SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("myarrayofcustomobjects", forStoring).commit();
//Get the string back from the SharedPreferences
String fromPrefs = prefs.getString("myarrayofcustomobjects","");
//Get the Object array back from the String `fromPrefs`
CustomProduct[] reInflated = gson.fromJson(fromPrefs,CustomProduct[].class);
Notes
If you already have a set of objects in an array, you'll need to inflate the array as shown above, create a new array with those elements + the one you want to add, convert them to a string again, and store them. Once this becomes too much of a hassle, you'll move to another means of persisting data for you app, but for as long as there are not that many, it should be ok.
Assuming
To get this to work, I'm assuming you have a Custom object named CustomProduct with the following definition:
public class CustomProduct {
String field1,field2;
public CustomProduct(String field1, String field2){
super();
this.field1 = field1;
this.field2 = field2;
}
#Override
public String toString() {
return "CustomProduct [field1="+field1+",field2="+field2+"]";
}
}
Update
User wants to show the results in a listview. You can define a custom adapter like the following to get it to work. Let this be the time for me to advise you to soon move towards RecyclerView instead of ListView but first tackle the problem you have, make it work, then improve upon it
public class CustomAdapter extends BaseAdapter{
private CustomProduct[] mProducts;
private LayoutInflater mInflater;
public CustomAdapter(Context context, CustomProduct[] products){
mProducts = products;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return mProducts.length;
}
public CustomProduct getItem(int i) {
return mProducts[i];
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View convertView, ViewGroup parent) {
//Purposely not doing view recycling for sake of clarity
View row = mInflater.inflate(R.layout.custom_row,parent,false);
//Set the data from the row
((TextView)row.findViewById(R.id.field1)).setText(getItem(i).field1);
((TextView)row.findViewById(R.id.field2)).setText(getItem(i).field2);
//Return the view
return row;
}
}
By setting this adapter to your ListView and creating the layout (which simply consists in two textviews with the given ids) you will get the following result. You can try removing the part where it creates the data after it's run the first time and leaving only the part where it fetches the data to ensure it's persisted.

ParseQueryAdapter; using class in Android

I feel like a broken record.
After many attempts, I have failed at getting a listview through Parse data to display a specific set of information.
Here is my model...this is all data from users:
#ParseClassName("Midwifefirm")
public class Midwifefirm extends ParseObject {
public Midwifefirm() {
// A default constructor is required.
}
//practice name
public String getPracticeName() {
return getString("practicename");
}
public void setPracticeName(String practicename) {
put("practicename", practicename);
}
//education
public String getEducation() {
return getString("education");
}
public void setEducation(String education) {
put("education", education);
}
//years in practice
public String getYearsinPractice() {
return getString("yearsinpractice");
}
public void setYearsinPractice(String yearsinpractice) {
put("yearsinpractice", yearsinpractice);
}
//practice philosophy
public String getPracticePhilosophy() {
return getString("practicephilosophy");
}
public void setPracticePhilosophy(String practicephilosophy) {
put("practicephilosophy", practicephilosophy);
}
I have this adapter; I am wondering what to place in the query section, as I just want to pull the data into the ListView that is defined in the data model:
public class CustomMidwifeAdapter extends ParseQueryAdapter<Midwifefirm> {
public CustomMidwifeAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<Midwifefirm>() {
public ParseQuery<Midwifefirm> create() {
// Here we can configure a ParseQuery to display
// only top-rated meals.
ParseQuery query = new ParseQuery("Midwives");
return query;
}
});
}
#Override
public View getItemView(Midwifefirm midwifefirm, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.activity_midwife_result_list, null);
}
//use midwifefirm as item view/list
super.getItemView(midwifefirm, view, parent);
// find in layout the practice name
TextView titleTextView = (TextView) view.findViewById(R.id.practicename);
//in the midwifefirm data model, call getPracticename
titleTextView.setText(midwifefirm.getString("practicename"));
// Add education view
TextView EducationView = (TextView) view.findViewById(R.id.education);
EducationView.setText(midwifefirm.getString("education"));
// Add yearsexperience view
TextView ExperienceView = (TextView) view.findViewById(R.id.yearsinpractice);
ExperienceView.setText(midwifefirm.getString("yearsinpractice"));
//Add practice philosophy view
TextView PracticePhilosophyView = (TextView) view.findViewById(R.id.practicephilosophy);
PracticePhilosophyView.setText(midwifefirm.getString("practicephilosophy"));
return view;
}
}
And here is the Main Activity:
public class MidwifeResultList extends ListActivity {
private ParseQueryAdapter<ParseObject> mainAdapter;
private CustomMidwifeAdapter midwifeListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialize main ParseQueryAdapter
mainAdapter = new ParseQueryAdapter<ParseObject>(this, Midwifefirm.class);
//which keys in Midwife object
mainAdapter.setTextKey("practicename");
mainAdapter.setTextKey("education");
mainAdapter.setTextKey("yearsinpractice");
mainAdapter.setTextKey("practicephilosophy");
// Initialize the subclass of ParseQueryAdapter
midwifeListAdapter = new CustomMidwifeAdapter(this);
// Default view is all meals
setListAdapter(mainAdapter);
}
Every time I run this, I get no results.
Thanks in advance for any help
Michael
I can tell you why I think it fails now and I can tell you why I'm very sure it will fail after you sort out the current issue.
It seems that you're trying to use different classes
#ParseClassName("Midwifefirm")
public class Midwifefirm extends ParseObject {
and
ParseQuery query = new ParseQuery("Midwives");
You need to be consistent and use the same name. Either use Midwives or Midwifefirm for both. Let's assume you picked the latter. You're also saying
all that is stored in the user table...wasn't sure if I needed to create new tables.
The query above wants to get all entries of type Midwives. If there's no such type, it'll return nothing. So you have two options:
In you Parse dashboard, reate a class Midwifefirm (don't forget to update the String inside #ParseClassName above) and store your Midwifefirm data in there. You don't need to change your query for this.
Add a column to your ParseUser class, such as type, that you can set to Midwifefirm or whatever if that user is a Midwifefirm or whatever. Then in your query you need to add:
ParseQuery query = new ParseQuery("Midwives");
query.whereEquals("type", "Midwifefirm");
I greatly prefer the former.
Anyway, once your done that, the issue is that you're not using a custom view for this. You're relying on the one provided by Android by default for ListActivity. I am fairly sure it doesn't have any of the fields you're after, so you should create a custom view for this, then at the top of onCreate in your Activity make sure you use it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_custom_view);
By the way, the following are redundant if you populate then in getItemView anyway:
mainAdapter.setTextKey("practicename");
mainAdapter.setTextKey("education");
mainAdapter.setTextKey("yearsinpractice");
mainAdapter.setTextKey("practicephilosophy");
One final advice: if you're still having issues, set breakpoints and do some investigations first. What you need to check is:
Whether you get anything at all from Parse when you do your query. Your adapter has an useful addOnQueryLoadListener that you may use to check whether anything's been retrieved at all.
If stuff is retrieved successfully, you need to check whether the list view is populated correctly. Again, use breakpoints, this time in getItemView maybe.
I'm going to do a wild guess here using the lovely brainwrecking API help of Parse.com about ParseQueryAdapters
Before continuing, may I mind you that my experience with ParseQueryAdapters is a minimum but I think I have a basic knowledge about them + I have some experience with Parse on its own. ANYHOW,
As an example they use both these
final ParseQueryAdapter adapter = new ParseQueryAdapter(this, "Midwives");
adapter.setTextKey("name");
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
and
// Instantiate a QueryFactory to define the ParseQuery to be used for fetching items in this
// Adapter.
ParseQueryAdapter.QueryFactory<ParseObject> factory =
new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("Midwives");
return query;
}
};
// Pass the factory into the ParseQueryAdapter's constructor.
ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(this, factory);
adapter.setTextKey("name");
// Perhaps set a callback to be fired upon successful loading of a new set of ParseObjects.
adapter.addOnQueryLoadListener(new OnQueryLoadListener<ParseObject>() {
public void onLoading() {
// Trigger any "loading" UI
}
public void onLoaded(List<ParseObject> objects, ParseException e) {
// Execute any post-loading logic, hide "loading" UI
}
});
// Attach it to your ListView, as in the example above
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
To start of, the reason why I think nothing is loading inside your list has to do with a little mixup between the initilization of your ParseQueryAdapter and your custom adapter.
You configure the basic adapter, and also initialize a custom adapter but you don't do anything with the custom adapter, tho the custom adapter seems to contain the logics to load your data model.
I think what you're looking for is something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialize main ParseQueryAdapter
mainAdapter = new CustomMidwifeAdapter<ParseObject>(this);
//which keys in Midwife object
mainAdapter.setTextKey("practicename");
mainAdapter.setTextKey("education");
mainAdapter.setTextKey("yearsinpractice");
mainAdapter.setTextKey("practicephilosophy");
// Default view is all meals
setListAdapter(mainAdapter);
}
All you need to pass is the context (aka "this"), and the constructor of your custom class will handle the factory internal
super(context, new ParseQueryAdapter.QueryFactory<Midwifefirm>() {
public ParseQuery<Midwifefirm> create() {
// Here we can configure a ParseQuery to display
// only top-rated meals.
ParseQuery query = new ParseQuery("Midwives");
return query;
}
});
Tho to be honest since you do:
new ParseQueryAdapter<ParseObject>(this, Midwifefirm.class);
I wonder if you'd need to change your "QueryFactory" to
super(context, new ParseQueryAdapter.QueryFactory<Midwifefirm>() {
public ParseQuery<Midwifefirm> create() {
// Here we can configure a ParseQuery to display
// only top-rated meals.
ParseQuery query = new ParseQuery(MidWifefirm.class);
return query;
}
});
Where you pass a class to the the query rather than the tableName, but I could be wrong on that one.
Either way I hope this has helped in some way!

Parse Nested Query Android

Ok been stuck on this for literally weeks, sorry for long question.
Using Parse, making a workout app for Android.
Database tables and columns that are relevant to my problem are:
Exercises
ID| name | description | Musclegroup
Workouts
ID| workoutName| userID
WorkoutExercises (basically a join table between the two)
ID| workoutID (pointer) | exerciseID (pointer)
So a user will be able to create a workout and add in the exercises they want.
So far I've already done:
User can go to category, browse the muscle group, view the exercises in that group
signup/login/logout, update profile
list the current workouts (not the exercises in them) -
I have just entered some exercises into a workout on the db as have gotten stuck on querying current exercises in that workout before worrying about inserting new ones.
The problem:
I'm trying to do a nested query to get the exercise name so once a user clicks Eg. Back Workout it should bring up a list Eg. Deadlift, Rows, Chin ups
So basically in SQL I want to:
Select name
from Exercises
where ID in (select exerciseID from workoutexercises where WorkoutID=xxxx)
Things i'm struggling on:
Making a nested query for a pointer, from what I have read on the net I need to use query.include("exerciseID"); which will tell Parse to include a full Exercise item that I can then use to query? Correct me if wrong? Code below - have I done it correctly?
I've learnt from and been using methods from: http://www.michaelevans.org/blog/2013/08/14/tutorial-building-an-android-to-do-list-app-using-parse/ where query data is put into a custom adapter that lists the data. It uses getters
and setters to save/retrieve String/int values, do I still use the getters for getting a string from within a pointer?
EG.
public String getName()
{
return getString("name");
}
As in once i'm "through" that pointer and in the Exercise table im assuming i'm still just getting the String name value as oppose to getting a ParseObject?
Now so far I have been able to get the custom adapter to put 2 horizontal bars across the screen that shows it knows i've put 3 items in workoutExercises but just not bringing up the text from Exercise name that I need from the nested query
Have a look at my screenshots to see what I mean.
Thank you very much for the help in advance.
Query so far:
public void getcurrentExercisesInWorkout() {
//set progress bar
setProgressBarIndeterminateVisibility(true);
ParseQuery<WorkoutExercises> query = ParseQuery.getQuery("WorkoutExercises");
query.include("exerciseId");
query.whereEqualTo("workoutId", mWorkoutId);
query.findInBackground(new FindCallback<WorkoutExercises>() {
#Override
public void done(List<WorkoutExercises> workoutExercises, ParseException error) {
if (workoutExercises != null) {
mWorkoutExercisesAdapter.clear();
mWorkoutExercisesAdapter.addAll(workoutExercises);
} else {
Log.d("error", error.getMessage());
}
}
});
//stop progress bar
setProgressBarIndeterminateVisibility(false);
}
Custom list Adapter:
//constructor - get current state of parsed object and list of objects retrieved from workout
public WorkoutExercisesAdapter(Context context, List<WorkoutExercises> objects) {
super(context, R.layout.row_item, objects);
this.mContext = context;
this.mWorkoutExercises = objects;
}
public View getView(int position, View convertView, ViewGroup parent)
{
//put each item into the listview
if(convertView == null)
{
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.row_item,null);
}
WorkoutExercises workoutExercises = mWorkoutExercises.get(position);
TextView nameView = (TextView) convertView.findViewById(R.id.row_name);
//this just calls a String getter - which isn't working - need it to get the Exercise name from within the pointer
nameView.setText(workoutExercises.getWorkoutExercise());
return convertView;
}
WorkoutExercises(stores the getters)
#ParseClassName("WorkoutExercises")
public class WorkoutExercises extends ParseObject {
public String exName;
public WorkoutExercises()
{
}
public String getWorkoutExercise()
{
return getString("name");
}
}
Running Android Studio in Debug mode I can literally see the data I am trying to put into the text field (see screenshot - how can I grab that value? See screenshot below
NOW WORKING - THE RESULT!
First, alter the WorkoutExercises object:
#ParseClassName("WorkoutExercises")
public class WorkoutExercises extends ParseObject {
//public String exName;
public static final String workoutID = "workoutID"
public static final String exerciseID = "exerciseID"
public Exercises getWorkoutExercise() {
return (Exercises)getParseObject(exerciseID);
}
public WorkoutExercises()
{
// not sure if it is allowed to define your own constructor?
// just a note
}
// WorkoutExercises does not have a 'name' col
//public String getWorkoutExercise()
//{
// return getString("name");
//}
}
I assume that Exercises at least contains something like:
#ParseClassName("Exercises")
public class Exercises extends ParseObject {
public static final String name = "name"
public String getName()
{
return getString(name);
}
}
Now, with the query on WorkoutExercises including workoutID, the Exercises object will be populated in the fetched query. This means you can do the following to get the name of the exercises object:
// workoutExercises returned from a query including workoutID
Exercises exercise = workoutExercises.getWorkoutExercise();
String name = exercise.getName();
// if Exercises has getters for description and Musclegroup
String description = exercise.getDescription();
String musclegroup= exercise.getMusclegroup();
Hope this sheds some light on the problem

Fill an ArrayList asynchronously to be displayed in a listview

When the user clicks on a button, a new ListFragment is displayed. This fragment will contain the list of the albums with their associated Artist's name.
I've created my own class AlbumItem (String name, String artist) with name being the Album's title and artist the corresponding artist name :
public class AlbumItem {
private String AlbumName;
private String AlbumArtist;
public AlbumItem(){
}
public AlbumItem(String name, String artist){
this.AlbumName = name;
this.AlbumArtist = artist;
}
public String getAlbumName() {
return AlbumName;
}
public void setAlbumName(String AlbumName) {
this.AlbumName = AlbumName;
}
public String getAlbumArtist() {
return AlbumArtist;
}
public void setAlbumArtist(String AlbumArtist) {
this.AlbumArtist = AlbumArtist;
}
}
Then I wrote my custom adapter which associates the Album's name and Artist's name with the correct TextView in my ListView's row.
So then I can declare an ArrayList of AlbumItem and fill it like this :
ArrayList<AlbumItem> arrayList;
arrayList.add(new AlbumItem ("Album's title", "Artist");
Now I have few questions :
1) Am I going the appropriate way ? I've always learnt to fill listviews like that and I'm very comfortable using this technique (Custom Item class + ArrayList + CustomAdapter), but I'm doing a Music player and I'd like to query the list of Albums and update the listview asynchronously so that the UI is not blocked. I don't know if it is possible to do it by loading data in a ArrayList the way I do it.
2) How to fill up this ArrayList asynchronously ? With LoaderManager/CursorLoader or Asyntask or something else ? (I'm targeting Android 4.0)
Thanks for your advice.
CursorLoader is a convenient way of loading your list, especially if you get the data from a database or another local data source. If your data comes from the network, it may be easier to get the data with an asynctask and load it in the list adapter. If you are familiar with one of these, use that.

How to display string response from db as one by one in Android?

I am new developer in android. I am working with soap object in my application for communicate with the .net db services.I am getting response as strings from DB server. But my intention is when I get a string from db server as response then imediatly view as text view similarly I am getting images encoded string.how to get response imedialty as view. I have written code as follows:
String xml="<spGetUserMessages><SearchLocation></SearchLocation><LoginUserID>"+Userid+"</LoginUserID></spGetUserMessages>";
I am sending request as XML to db server
The response from db server is in list:
List<MessageClass> response=new ParseXml().getUserMessages(new Generic().getMessages(xml));
String messages=new String[response.size()];
for(int i=0;i<response.size();i++)
{
//the response values are saved in messages array
messages[i]=response.get(i).getmessage();
}
I have written a base adapter class in that class we have a method as getView I have implemented as follows:
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item, null);
TextView text=(TextView)vi.findViewById(R.id.text);;
ImageView image=(ImageView)vi.findViewById(R.id.image);
Log.v("rrrrrrrrrr", "rrrrrrrr"+messages[position]);
text.setText(messages[position]);
}
From the above code I am displaying all messages at a time. But in this situation the response is taking time then I am getting blank screen. Here my intention is when I get a string response then I will view that string as text view next time next similarly untill reposnse size has completed.
What you can do is display the Listview without waiting for response and from background thread add the responses to messages and call
mAdapter.notifyDatasetChanged();
This is concept of LazyLoading and I hope it should work
Update
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
use the AsyncTask class to work in background process like this way
private String messages[];
class BackgroundTask extends AsyncTask<Void, Void, Void>{
public void doInBackground(Void... arg){
List<MessageClass> response=new ParseXml().getUserMessages(new Generic().getMessages(xml));
messages=new String[response.size()];
for(int i=0;i<response.size();i++){
//the response values are saved in messages array
messages[i]=response.get(i).getmessage();
}
}
public void postExecute(Void result){
// here you initialize the listview so the getview() method will call after fetching the response and store into the array.
}
}

Categories

Resources