Inquire variable in other class / activity if it is filled - java

I am beginner in Java and Android. I searched yesterday a whole day for a solution. I want to check a variable in second activity if it is filled. Or ask the methode "loadAngebote" if it has a return value. The methode that is executed to get data is:
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>>{
String data ="";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params){
try
{
URL url = new URL("http://url/file.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €","Von: " + all_von[i],"Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
return dataList; <--------------------------------------------
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult){
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
I need to check if dataList is filled in an other class of my app:
static String getLocationResultTitle(Context context, List<Location> locations) {
if(?????dataList_is_filled?????){
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}else{
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}

Updated Answer
Here is your AngeboteActivity
public class AngeboteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public enum DataHolder {
INSTANCE;
private ArrayList<ArtikelAngebot> mObjectList;
public static boolean hasData() {
return INSTANCE.mObjectList != null;
}
public static ArrayList<ArtikelAngebot> getData() {
final ArrayList<ArtikelAngebot> retList = INSTANCE.mObjectList;
INSTANCE.mObjectList = null;
return retList;
}
public static void setData(final ArrayList<ArtikelAngebot> objectList) {
INSTANCE.mObjectList = objectList;
}
}
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>> {
String data = "";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params) {
try {
URL url = new URL("http://url/file.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i = 0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €", "Von: " + all_von[i], "Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
DataHolder.setData(dataList);
return dataList;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult) {
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
}
And Here is your Utils class
public class Utils {
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
} else {
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
}

Ok now Your Activity looks good..
Now in Utils class change if(loadAngebote.DataHolder.hasData()) to if (AngeboteActivity.DataHolder.hasData())
Here:-
public class Utils {
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
} else {
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
}

UPDATED ANSWER My Angebote Activity:
public class AngeboteActivity extends AppCompatActivity {
public static TextView data;
public static ListView mListView;
private static final String TAG = "AngeboteActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_angebote);
data = (TextView) findViewById(R.id.data);
mListView = (ListView) findViewById(R.id.listView);
new loadAngebote().execute();
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object Inhalt = parent.getAdapter().getItem(position);
final Intent intent = new Intent(AngeboteActivity.this, AngeboteRequestInfoActivity.class);
Bundle bundle = new Bundle();
//Objekt Serialisieren
bundle.putSerializable("object", (Serializable) Inhalt);
//Objekt in Intent Extras packen
intent.putExtras(bundle);
AngeboteActivity.this.startActivity(intent);
}
});
}
private class QueryResult {
ArrayList<ArtikelAngebot> dataList;
public QueryResult(ArrayList<ArtikelAngebot> dataList) {
this.dataList = dataList ;
}
}
public enum DataHolder {
INSTANCE;
private ArrayList<ArtikelAngebot> mObjectList;
public static boolean hasData() {
return INSTANCE.mObjectList != null;
}
public static void setData(final ArrayList<ArtikelAngebot> objectList) {
INSTANCE.mObjectList = objectList;
}
public static ArrayList<ArtikelAngebot> getData() {
final ArrayList<ArtikelAngebot> retList = INSTANCE.mObjectList;
INSTANCE.mObjectList = null;
return retList;
}
}
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>>{
String data ="";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params){
try
{
URL url = new URL("http://url/request.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €","Von: " + all_von[i],"Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
DataHolder.setData(dataList);
return dataList;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult){
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
My Utils.java class
public class Utils {
final static String KEY_LOCATION_UPDATES_REQUESTED = "location-updates-requested";
final static String KEY_LOCATION_UPDATES_RESULT = "location-update-result";
static void setRequestingLocationUpdates(Context context, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_LOCATION_UPDATES_REQUESTED, value)
.apply();
}
static boolean getRequestingLocationUpdates(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_LOCATION_UPDATES_REQUESTED, false);
}
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
static void sendNotification(Context context, String notificationDetails) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(context, AngeboteActivity.class);
notificationIntent.putExtra("from_notification", true);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(AngeboteActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
// Notification Einstellungen
builder.setSmallIcon(R.drawable.ic_launcher)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher))
.setColor(Color.RED)
.setContentTitle("Ihre Apotheke vor Ort")
.setContentText(notificationDetails)
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
/**
* Returns the title for reporting about a list of {#link Location} objects.
*
* #param context The {#link Context}.
*/
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}else{
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
/**
* Returns te text for reporting about a list of {#link Location} objects.
*
* #param locations List of {#link Location}s.
*/
private static String getLocationResultText(Context context, List<Location> locations) {
if (locations.isEmpty()) {
return "Unbekannte Position";
}
StringBuilder sb = new StringBuilder();
for (Location location : locations) {
sb.append("(");
sb.append(location.getLatitude());
sb.append(", ");
sb.append(location.getLongitude());
sb.append(")");
sb.append("\n");
}
return sb.toString();
}
static void setLocationUpdatesResult(Context context, List<Location> locations) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(KEY_LOCATION_UPDATES_RESULT, getLocationResultTitle(context, locations)
+ "\n" + getLocationResultText(context, locations))
.apply();
}
static String getLocationUpdatesResult(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(KEY_LOCATION_UPDATES_RESULT, "");
}
}

Related

Parsing multiple JsonObject and JsonArray

I have some issues with using multiple jsonobjects I want to use "posts" and "attachments" jsonobjects.
but I tried to use the line and another for loop for attachments jsonObject but it doesnt work.
String postInfo = jsonObject.getString("attachments");
My Json looks like this:
{"posts":[
{"title":"Title","content":"Post content"}
]
}
{"attachments":[
{"url":"http://www.something.com"}
]
}
Java code:
public class NewsActivity extends FragmentActivity {
ViewPager viewPager;
int category;
ArrayList titleList;
ArrayList postList;
ArrayList imgList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Intent i = getIntent();
category=i.getIntExtra("locationInfo",-1);
try {
String encodedCatName = URLEncoder.encode(Integer.toString(category), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://www.something.co/api/get_category_posts/?id=" + encodedCatName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
postList = new ArrayList();
titleList = new ArrayList();
imgList = new ArrayList();
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not find", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String postInfo = jsonObject.getString("posts");
Log.i("Content", postInfo);
JSONArray arr = new JSONArray(postInfo);
JSONArray attachments = jsonObject.getJSONArray("attachments");
for(int i=0; i< attachments.length(); i++){
String url = "";
url = attachments.getJSONObject(i).getString("url");
imgList.add(url);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = "";
String post = "";
title = jsonPart.getString("title");
post = jsonPart.getString("content");
if (title != "" && post != "") {
message += title + ": " + post + "\r\n";
titleList.add(title);
postList.add(post);
}
}
viewPager = (ViewPager) findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager(),category,titleList,postList,imgList);
viewPager.setAdapter(swipeAdapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find ", Toast.LENGTH_LONG);
}
}
}
}
The type related to 'attachments' is an array, therefore you should call something like:
JSONArray attachments = jsonObject.getJSONArray("attachments")
for(int i=0; i< attachments.length(); i++){
attachments.getJSONObject(i).getString("url");
}

java.util.ConcurrentModificationException in Android [duplicate]

This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 6 years ago.
I am writing a piece of code which displays in an expandable list using information from an AsyncTask and a pre defined HashMap. But it is throwing java.util.ConcurrentModificationException. My code is as follows:
AsnycTask
private class BackTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
ArrayList<String> name;
ArrayList<Integer> quantity;
Map<String, Map<String, Integer>> cart_names1 = new HashMap<String, Map<String, Integer>>();
public BackTask(ArrayList<String> name, ArrayList<Integer> quantity) {
this.name = name;
this.quantity = quantity;
}
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ha);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void... arg0) {
InputStream is = null;
String result = "";
try {
String link = "http://chutte.co.nf/get_item_prices.php?";
for (int b = 0; b < name.size(); b++) {
link += "names[]" + "=" + name.get(b) + "&";
}
for (int a = 0; a < quantity.size(); a++) {
link += "quantities[]" + "=" + quantity.get(a);
if (a != quantity.size() - 1) {
link += "&";
}
}
Log.e("ERROR", link);
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
} catch (Exception e) {
if (pd != null) pd.dismiss();
Log.e("ERROR", e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
is.close();
result = builder.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
try {
result = result.substring(result.indexOf("["));
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, Integer> temmap = new HashMap<>();
String temname = jsonObject.getString("Name");
temmap.put("First", jsonObject.getInt("First"));
temmap.put("Second", jsonObject.getInt("Second"));
temmap.put("Third", jsonObject.getInt("Third"));
Log.e("ERROR", temmap.get("First").toString());
cart_names1.put(temname, temmap);
}
strhold2.clear();
strhold2.add("First");
strhold2.add("Second");
strhold2.add("Third");
String[] strhold1 = new String[strhold2.size()];
for (int i56 = 0; i56 < strhold2.size(); i56++) {
strhold1[i56] = strhold2.get(i56);
}
System.out.println(cart_names1);
Log.e("ERROR", Integer.toString(cart_names1.size()) + "IN LATEST");
if (cart_names1.size() > 1) {
System.out.println(cart_names1.size());
System.out.println(strhold2.size());
Combination.printCombination(cart_names1, strhold1, strhold2.size(), cart_names1.size(), 2);
ArrayList<String> wrong = Permutation.getlist();
System.out.println(wrong + "this is final");
setalldata(wrong);
System.out.println(wrong);
couldthis.clear();
couldthis.addAll(wrong);
} else {
Single_Permutation.getpermute(cart_names1);
System.out.println(Single_Permutation.singlelist);
couldthis.clear();
couldthis.addAll(Single_Permutation.singlelist);
setalldata(Single_Permutation.singlelist);
Log.e("ERROR", "thisis the list 1" + getdataformap());
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
/*SetMap setMap = new SetMap(getdataformap());
setMap.execute();*/
if (pd != null){ pd.dismiss();}
ListFragment.addtolist(getdataformap());
Log.e("ERROR", "This is putmap i" + getdataformap());
SetMap setMap =new SetMap(getdataformap());
setMap.execute();
}
}
}
Fragment(with expandable list)
public static class ListFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static ExpandableListView expandablelistview;
public static CustomExpandableListAdapter expandableadapter;
public static HashMap<Fitems, List<Fnitems>> datapforput = new HashMap<>();
public static List<Fitems> mainforput = new ArrayList<>();
public static View view;
public static Context getha;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = inflater.inflate(R.layout.activity_listfragment, container, false);
//doddata();
expandablelistview = (ExpandableListView) view.findViewById(R.id.expandableListView);
expandableadapter = new CustomExpandableListAdapter(((Result) getActivity()).getha(), mainforput, datapforput);
expandablelistview.setAdapter(expandableadapter);
getha = ((Result) getActivity()).getha();
return view;
}
#Override
public void onStart() {
super.onStart();
Permutation.finallist = new ArrayList<>();
Single_Permutation.singlelist = new ArrayList<>();
/* doddata();
expandablelistview = (ExpandableListView) view.findViewById(R.id.expandableListView);
expandableadapter = new CustomExpandableListAdapter(((Result)getActivity()).getha(),mainforput,datapforput);
expandablelistview.setAdapter(expandableadapter);*/
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static void doddata() {
Fitems fitems1 = new Fitems();
Fitems fitems2 = new Fitems();
Fnitems fnitems1 = new Fnitems();
Fnitems fnitems2 = new Fnitems();
Fnitems fnitems3 = new Fnitems();
Fnitems fnitems4 = new Fnitems();
fitems1.setName("AAA");
fitems2.setName("BBB");
fnitems1.setName("AAAa");
fnitems2.setName("AAAb");
fnitems3.setName("BBBa");
fnitems4.setName("BBBb");
List<Fnitems> listfnitem1 = new ArrayList<>();
List<Fnitems> listfnitem2 = new ArrayList<>();
listfnitem1.add(fnitems1);
listfnitem1.add(fnitems2);
listfnitem2.add(fnitems3);
listfnitem2.add(fnitems4);
datapforput.put(fitems1, listfnitem1);
datapforput.put(fitems2, listfnitem2);
mainforput.add(fitems1);
mainforput.add(fitems2);
//Log.e("ERROR", "thisis the list for god's sake " + Result.couldthis+datapforput.toString());
if (Result.couldthis.size() > 0) {
for (int i = 0; i < (Result.couldthis).size(); i++) {
for (Map.Entry<Fitems, List<Fnitems>> entry : datapforput.entrySet()) {
if (Result.couldthis.get(i).equals(entry.getKey().getName())){
Fnitems fnitems5 = new Fnitems();
fnitems5.setName(Search_multiple.cart_records.get(i).getName());
entry.getValue().add(fnitems5);
}else {
Fitems fitems3 = new Fitems();
fitems3.setName(Result.couldthis.get(i));
Fnitems fnitems5 = new Fnitems();
fnitems5.setName(Search_multiple.cart_records.get(i).getName());
List<Fnitems> listfnitem3 = new ArrayList<>();
listfnitem3.add(fnitems5);
datapforput.put(fitems3, listfnitem3);
mainforput.add(fitems3);
}
}
}
}
}
public static ListFragment newInstance() {
ListFragment fragment = new ListFragment();
Log.e("ERROR", "man .... " + fragment.getTag());
return fragment;
}
public static void addtolist(ArrayList<String> dataforputting) {
// Log.e("ERROR", "thisis the list 3" + (dataforputting));
//if (expandableadapter != null){
expandableadapter.clear();//}
//Log.e("INFO", "This is mainforput" + mainforput + "This is dataforput" + datapforput);
doddata();
//Log.e("INFO", "This is mainforput" + mainforput + "This is dataforput" + datapforput);
expandableadapter = new CustomExpandableListAdapter(getha, mainforput, datapforput);
expandablelistview.setAdapter(expandableadapter);
}
}
Stack
07-13 18:16:11.955 17339-17339/nf.co.riaah.chutte E/ERROR: Inside populate Second
07-13 18:16:11.986 17339-17339/nf.co.riaah.chutte E/AndroidRuntime: FATAL EXCEPTION: main
Process: nf.co.riaah.chutte, PID: 17339
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
at java.util.HashMap$EntryIterator.next(HashMap.java:824)
at java.util.HashMap$EntryIterator.next(HashMap.java:822)
at nf.co.riaah.chutte.Result$ListFragment.doddata(Result.java:199)
at nf.co.riaah.chutte.Result$ListFragment.addtolist(Result.java:230)
at nf.co.riaah.chutte.Result$SetMap.onPostExecute(Result.java:1049)
at nf.co.riaah.chutte.Result$SetMap.onPostExecute(Result.java:967)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
This means that you're modifying a collection while trying to iterate over it. It could be all in the same place or it could be from different threads.
for each loop are generally fail fast , that you can 't change the collection ( as for each internally use iterator ) .
instead of using " for (Map.Entry> entry : datapforput.entrySet()) "
create an iterator and then iterate over map again , don't forget to assign
iterator reference to newly created entrySet . just reassign iterartor reference each time in while / for whichever loop you use to iterate .
}

Java/Android scoop

Why does Log.d("Test", "" + ListOfAttractions3.size() + ""); Return 0 when Log.d("Test2", "" + ListOfAttractions3.size() + ""); returns 2 even thoughDatabseRequest(); is called first? Some how Log 2 is also printed last but I can't see why?
Code:
public class Testlist extends Activity {
List<Attractions> ListOfAttractions3 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testlist);
DatabseRequest();
Log.d("Test", "" + ListOfAttractions3.size() + "");
}
/*private void reFreshDisplay(){
ListView listView2 = (ListView) findViewById(R.id.listView2);
ArrayAdapter<Attractions> adapter = new ArrayAdapter<Attractions>(this, android.R.layout.simple_list_item_1, ListOfAttractions3);
listView2.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
private void DatabseRequest(){
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
int i = 0;
while(i < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
boolean success;
if (jsonObject.getBoolean("success")) success = true;
else success = false;
if (success) {
String attractionname = jsonObject.getString("attractionname");
double lng = jsonObject.getDouble("longitude");
double lat = jsonObject.getDouble("latitude");
int Rating = jsonObject.getInt("rating");
Attractions attraction = new Attractions(attractionname, lng, lat, Rating);
ListOfAttractions3.add(attraction);
Log.d("Test2", "" + ListOfAttractions3.size() + "");
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Testlist.this);
builder.setMessage("Connection to server Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
AttractionRequest attractionRequest = new AttractionRequest(responseListener);
RequestQueue queue2 = Volley.newRequestQueue(Testlist.this);
queue2.add(attractionRequest);
}
}

using shared preferences to store arraylist, null object returned

I have an ArrayList listwriter which I populate using this AsyncTask.
class LoadAllGamesWhenNull extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
// *//**
// * Before starting background thread Show Progress Dialog
// *//*
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// *//**
// * getting All products from url
// *//*
protected String doInBackground(String... args) {
// Building Parameters
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_all_games);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", name));
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Response:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
Log.d("sb", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("json", jObj.toString());
try {
allgames = jObj.getJSONArray(TAG_BET);
Log.d("allgames", allgames.toString());
ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
Log.d("id", id);
Log.d("user", user);
Log.d("returns", returns);
Log.d("stake", stake);
Log.d("status", status);
Log.d("teams", Teams);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
if (status.equals("open")) {
useroutcomes.put(id.substring(0, 10), Teams);
}
listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, "","",Teams));
Log.d("map", map.toString());
// adding HashList to ArrayList
bet.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
String ultparam = "";
int i = 0;
for (HashMap<String, String> a : bet) {
String teams = a.get(TAG_TEAMS);
Map<String, String> listofteams = new HashMap<>();
Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
Matcher m = p.matcher(teams);
Log.d("printa", teams);
while (m.find()) {
listofteams.put(m.group(1), m.group(2));
}
Log.d("dede", listofteams.toString());
String c = "";
for (String x : listofteams.keySet()) {
String b = x + ",";
c = c + b;
}
Log.d("C", c);
c = c.substring(0, c.lastIndexOf(","));
// Log.d("Cproc", c);
ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
passtocheck.add(listofteams);
allopens.put(Integer.toString(i), a.get(TAG_STATUS));
i++;
i++;
}
ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
Log.d("ULTPARAM", ultparam);
CheckBet checker = new CheckBet(ultparam, passtocheck);
HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
Log.d("Finaloutcomes", finaloutcomes.toString());
finaloutcomess = finaloutcomes.toString();
for (String x : finaloutcomes.keySet()) {
for (int p = 0; p < listwriter.size(); p++) {
if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
for (int r = 0; r < finaloutcomearray.length; r++) {
Log.d("finaloutcomearray", finaloutcomearray[r]);
Log.d("useroutcomearray", useroutcomearray[r]);
String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
String[] induseroutcomearray = useroutcomearray[r].split("\\)");
for (int d = 0; d < indfinaloutcomesarray.length; d++) {
Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
Log.d("induseroutcome", induseroutcomearray[d]);
finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));
}
}
Log.d("FINALHASHfinal", finalhash.toString());
listwriter.get(p).setActualselections(finalhash.toString());
listwriter.get(p).setUserselections(userhash.toString());
Log.d("USERHASHfinal", userhash.toString());
listwriter.get(p).setStatus("won");
for (String id : userhash.keySet()) {
if (finalhash.get(id).equals("null")) {
listwriter.get(p).setStatus("open");
} else if (!(finalhash.get(id).equals(userhash.get(id)))) {
listwriter.get(p).setStatus("lost");
break;
}
}
finalhash.clear();
userhash.clear();
currentitem = listwriter.get(p);
if (currentitem.getStatus().equals("open")) {
} else {
if (currentitem.getStatus().equals("won")) {
valuechange = valuechange + currentitem.getReturns() - (currentitem.getStake());
}
String c = currentitem.getId() + "," + currentitem.getStatus() + "//";
updateparam = updateparam + c;
Log.d("UPDATEPARAM1", updateparam);
}
}
}
}
Log.d("Listwriterbefore",listwriter.toString());
session.setListwriter(listwriter);
new UpdateBetStatus().execute();
Intent g = new Intent(loadingscreen.this,DisplayAllBets.class);
startActivity(g);
finish();
}}
This is done on my loadscreen Activity and I want to set the listwriter to my SharedPreferences so that I can use it in another Activity. This is my session manager class. The logging in the AsyncTask shows me that the listwriter gets populated correctly. However, when I call on the getlistwriter in my other class I receive an empty ArrayList. I can't see where the error is.
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "AndroidHiveLogin";
private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
public static final String USERNAME = "username";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public ArrayList<BetDisplayer> getListwriter() {
return listwriter;
}
public void setListwriter(ArrayList<BetDisplayer> listwriter) {
this.listwriter = listwriter;
}
public void setLogin(boolean isLoggedIn, String username) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.putString(USERNAME, username);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(USERNAME, pref.getString(USERNAME, null));
// return user
return user;
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}}
Code used to retrieve listwriter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
menu menu = (menu)
getFragmentManager().findFragmentById(R.id.fragment);
menu.updateinfo(getName());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.USERNAME);
listwriter = session.getListwriter();
AppController class :
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
private ArrayList<HashMap<String, String>> gamesList;
public ArrayList<HashMap<String, String>> getGamesList() {
return gamesList;
}
public void setGamesList(ArrayList<HashMap<String, String>> gamesList) {
this.gamesList = gamesList;
}
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
In your SessionManager you're not saving your List into SharedPrefs. You should do something like this:
public static final String MY_LIST = "my_list";
private static final Type LIST_TYPE = new TypeToken<List<BetDisplayer>>() {}.getType();
to save:
public void setListwriter(ArrayList<BetDisplayer> listwriter) {
this.listwriter = new ArrayList<BetDisplayer>(listwriter);
mPrefs.edit()
.putString(MY_LIST, new Gson().toJson(listwriter));
.commit();
}
to load:
public ArrayList<BetDisplayer> getListwriter() {
if (listwriter == null) {
listwriter = new Gson().fromJson(mPrefs.getString(MY_LIST, null), LIST_TYPE);
if(listwriter == null){
listwriter = new ArrayList<BetDisplayer>();
}
}
return listwriter;
}
Your BetDisplayer must implements Serializable.
See here: Android array to Sharedpreferences with Gson
To use Gson just add this dependency: 'com.google.code.gson:gson:2.3.1' or download the .jar
UPDATE:
Create a Singleton that holds one reference only to your SharedPreferences editor, it's just a will guess but I think you are using different context to get your editor and that could be the problem (UPDATE 2: it's not, check here, but the Singleton approach it's a plus):
private static SharedPreferences mPrefs;
private static SessionManager sInstance = null;
protected SessionManager() {
mPrefs = AppController.getInstance().getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static SessionManager getInstance() {
if (sInstance == null) {
sInstance = new SessionManager();
}
return sInstance;
}
And when you need to use SharedPreferences use SessionManager().getInstance().someMethod();

JSON parsing android

I need advice about my code.
I'm trying to parse a JSON array generated by the PHP function json_encode().
My json:
{"data": [{"streamer":"froggen","yt_length":"25078"},{"streamer":"wingsofdeath","yt_length":"8979"},{"streamer":"guardsmanbob","yt_length":"4790"},{"streamer":"kaostv","yt_length":"4626"},{"streamer":"kungentv","yt_length":"3883"},{"streamer":"destiny","yt_length":"3715"},{"streamer":"zekent","yt_length":"3428"},{"streamer":"athenelive","yt_length":"1673"},{"streamer":"frommaplestreet","yt_length":"1614"},{"streamer":"keyorikeys","yt_length":"1410"},{"streamer":"riotgamesturkish","yt_length":"1397"},{"streamer":"vman7","yt_length":"1022"},{"streamer":"tiensinoakuma","yt_length":"967"},{"streamer":"affenklappe","yt_length":"748"},{"streamer":"teamkeyd","yt_length":"747"},{"streamer":"lagtvmaximusblack","yt_length":"683"},{"streamer":"lolgameru","yt_length":"665"},{"streamer":"gruntartv","yt_length":"585"},{"streamer":"entenzwerg","yt_length":"579"},{"streamer":"lolgameru_cauthonpro","yt_length":"506"},{"streamer":"basickz","yt_length":"488"},{"streamer":"ilysuiteheart","yt_length":"491"},{"streamer":"kireiautumn","yt_length":"485"},{"streamer":"ultimavv","yt_length":"471"}]}
Java class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String response = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And my activity:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://ololo.tv/vasa";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_STREAMER = "streamer";
private static final String TAG_VIEWERS = "yt_length";
// contacts JSONArray
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser Parser = new JSONParser();
// getting JSON string from URL
JSONObject json = null;
json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.streamer)).getText().toString();
String viewers_count = ((TextView) view.findViewById(R.id.viewers)).getText().toString();
//String url = ((TextView) view.findViewById(R.id.url)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_STREAMER, name);
in.putExtra(TAG_VIEWERS, viewers_count);
//in.putExtra(TAG_PHONE_MOBILE, url);
startActivity(in);
}
});
}
}
I tried using breakpoints, and see that when I put a breakpoint after GetEntity, the program doesn't get there because it crashed early, or something.
This my async task.
public class ParsingTask extends AsyncTask<String, Void, Void>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
return null;
}
protected void onProgressUpdate() {
}
protected void onPostExecute() {
}
}
ListAdapter error, seems like something wrong in "this". This my version how cut off code, where it stop return variables. Sorry for bad english, but i hope you understand me :)
Add my php json maker. Mb problem there?!
<?php
mysql_connect("localhost","root","");
if (!mysql_select_db("ololo")) {
echo "Unable to select ololo: " . mysql_error();
}
$sql=mysql_query("select streamer, yt_length from pm_videos where category='1'");
if(!$sql) exit("Error - ".mysql_error().", ".$tmp_q);
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
$json = json_encode($output);
header('Content-Type: application/json');
print "{\"data\": ${json}}";
mysql_close();
?>
You programm crashes because you are running
json = Parser.getJSONFromUrl(url);
in the UI Thread context. You have to use an AsyncTask
Code looks good. The only problem is that
public class ParsingTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
return dataList;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> dataList) {
ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
}
Have you heard about gson (docs)?
public static final class Content {
#SerializedName("streamer") // you don't need to specify this, JFYI
String streamer;
#SerializedName("yt_length") // you don't need to specify this, JFYI
String yt_length;
}
public static final class Data {
#SerializedName("data")
List<Content> data;
}
public static void main (String[] args) {
Gson gson = new GsonBuilder().create();
Data data = gson.fromJson(jsonString, Data.class);
}
And remember, you cannot call network operations on UI thread! this is reason of what you have for now.
json data
[
-{
Cat_Id: 21
Cat_Title: "Electronics"
Cat_Description: null
Cat_Status: 0
Cat_CreatedBy: 0
Cat_CreatedDate: "0001-01-01T00:00:00"
Cat_UpdatedBy: 0
Cat_UpdatedDate: "0001-01-01T00:00:00"
}
Category class
public class Category {
public int Cat_Id;
public String Cat_Title = null;;
public Category() {
}
public int getCat_Id() {
return Cat_Id;
}
public void setCat_Id(int Cat_Id) {
this.Cat_Id = Cat_Id;
}
}
BaseActivity
public class BaseActivity extends Activity {
public ProgressDialog progressDialog;
public SharedPreferences prefs;
public JSONObject jsonObject;
public JSONObject jsonObject1;
public static String pref_setting = "Category_setting";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading..");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
Preferences.AppContext = this;
}
protected void onStop() {
super.onStop();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
Soap
public class Soap {
// public static String BaseURL = "";
public static String BaseURL = "";
public static String imgURL = "";
public static String getSoapResponseByGet(String postFixOfUrl)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(BaseURL + postFixOfUrl);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String xmlString = EntityUtils.toString(entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
public static String getSoapResponse(String postFixOfUrl)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
StringEntity se = new StringEntity("", HTTP.UTF_8);
se.setContentType("text/xml");
httpPost.setHeader("Content-Type", "text/xml;charset=utf-8");
httpPost.setEntity(se);
HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity r_Entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_Entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
public static String getSoapResponseByPost(String postFixOfUrl,
ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity r_Entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_Entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
// ////////// api for Category //////////////
http://sharafdg.digitarabia.com/sharafdg/api/Category
public static String apiGetCategory() throws ClientProtocolException,
IOException {
String result = Soap.getSoapResponseByGet("api/Category");
Log.e("SOAP", result);
return result;
}
public static String apiGetstore(int catid, int brandid, int modelid,
String variant) throws ClientProtocolException, IOException {
String result = Soap.getSoapResponseByGet("api/stores/?catid=" + catid
+ "&brandid=" + brandid + "&modelid=" + modelid + "&variant="
+ variant);
Log.e("SOAPSTORE", "api/stores/?catid=" + catid);
Log.e("SOAPSTORE", "api/stores/?&brandid=" + brandid);
Log.e("SOAPSTORE", "api/stores/?&modelid=" + modelid);
Log.e("SOAPSTORE", "api/stores/?&variant=" + variant);
return result;
}
-------------- post method hoy to -----------------
http://kallapp.madword-media.co.uk/company.php?category_id=11
http://kallapp.madword-media.co.uk/categories.php
public static String apiGetCategory() throws ClientProtocolException,
IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
String result = Soap.getSoapResponseByPost("categories.php",
alNameValuePairs);
return result;
}
public static String apiGetcompanies(String category_id)
throws ClientProtocolException, IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
// NameValuePair nameValuePairs = new BasicNameValuePair("",
// category_id);
// alNameValuePairs.add(nameValuePairs);
String result = Soap.getSoapResponse("company.php?category_id="
+ category_id);
Log.e("SOAP", result);
return result;
}
public static String apiGetDepaName(String category_id, String
company_id)
throws ClientProtocolException, IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("category_id",
category_id);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("company_id", company_id);
alNameValuePairs.add(nameValuePair);
String result =
Soap.getSoapResponseByPost("department.php?",alNameValuePairs);
return result;
}
Category_list
public class Category_list extends BaseActivity {
int currentCategoryid;
private ArrayList<Category> cat = new ArrayList<Category>();
ArrayList<String> list = new ArrayList<String>();
Spinner spinner;
Button btncompare;
private int catid;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setContentView(R.layout.activity_webservices);
spinner = (Spinner) findViewById(R.id.spinner);
btncompare = (Button) findViewById(R.id.btncompare);
spinner.setOnItemSelectedListener(new OnItemSelected());
new getCategoryTask().execute();
btncompare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), Store.class);
intent.putExtra("catid", catid);
startActivity(intent);
}
});
}
public class OnItemSelected implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// ((TextView) arg0.getChildAt(0)).setTextColor(Color.GREEN);
catid = cat.get(arg2).Cat_Id;
String cateid = String.valueOf(catid);
Log.e("cateid_category", cateid);
// new getBrandTask().execute();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
private class getCategoryTask extends AsyncTask<Void, Void, Void> {
Category category;
String categoryJsonStr;
public getCategoryTask() {
category = new Category();
}
protected void onPreExecute() {
super.onPreExecute();
// progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
-----------------------admin email-pass-------------
JSONObject jsonObject = new JSONObject(userJsonStr);//
jsonUserArray.getJSONObject(i);
currentUserid = jsonObject.getInt("Use_Id");
if (currentUserid > 0) {
if (!jsonObject.isNull("Use_Id")) {
id = jsonObject.getInt("Use_Id");
}
}
--------------------kallapp---------
try {
Log.i("categoryJsonStr", categoryJsonStr);
JSONObject jsonObject = new JSONObject(categoryJsonStr);
JSONArray jsonCatArray = jsonObject.getJSONArray("categories");
for (int i = 0; i < jsonCatArray.length(); i++) {
Category objcategory = new Category();
jsonObject = jsonCatArray.getJSONObject(i);
--------------------------------------------------------------
try {
// categoryJsonStr = Soap.apiGetCategory();
Log.e("categoryJsonStr", categoryJsonStr);
JSONArray jsonCatArray = new JSONArray(categoryJsonStr);
Category category = new Category();
// category.Cat_Id = -1;
category.Cat_Title = "Select Category";
cat.add(category);
list.add(category.Cat_Title);
for (int i = 0; i < jsonCatArray.length(); i++) {
Category objcategory = new Category();
JSONObject jsonObject = jsonCatArray.getJSONObject(i);
currentCategoryid = jsonObject.getInt("Cat_Id");
if (!jsonObject.isNull("Cat_Title")) {
objcategory.setCat_Title(jsonObject
.getString("Cat_Title"));
}
if (!jsonObject.isNull("Cat_Id")) {
objcategory.setCat_Id(jsonObject.getInt("Cat_Id"));
}
cat.add(objcategory);
list.add(objcategory.Cat_Title);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public void onPostExecute(Void result) {
super.onPostExecute(result);
// progressDialog.dismiss();
spinner.setAdapter(new ArrayAdapter<String>(Category_list.this,
android.R.layout.simple_spinner_item, list));
spinner.setSelection(0, true);
}
}
}
-------------more than one item fill--------
store_lists.add(objStore_list);
public void onPostExecute(Void result) {
super.onPostExecute(result);
store_adapter = new Store_adapter(Store.this, store_lists);
lv_store.setAdapter(store_adapter);
store_adapter.notifyDataSetChanged();
}
Preferences
public class Preferences {
public static Context AppContext = null;
public static String categoryid;
public static boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
Store_adapter
private Context mContext;
private int ImageCount;
private ArrayList<Store_list> store_lists = new ArrayList<Store_list>();
public ImageLoader imageLoader;
ImageView imgsave, imgpackage, img_up_arrow, img_dun_arrow;
TextView txtsave;
RelativeLayout relatv;
public Store_adapter(Context c, ArrayList<Store_list> store_lists) {
mContext = c;
this.store_lists = store_lists;
this.ImageCount = store_lists.size();
imageLoader = new ImageLoader(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
// ImageCount = store_lists.size();
return this.ImageCount;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
this.ImageCount = store_lists.size();
}
public void remove(int position) {
store_lists.remove(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.storelist, parent, false);
TextView name = (TextView) vi.findViewById(R.id.txtprise);
ImageView imgview = (ImageView) vi.findViewById(R.id.imgve);
Store_list list = store_lists.get(position);
imageLoader.DisplayImage(list.Store_logo, imgview);
name.setText(String.valueOf(list.Mod_Price));
return vi;
}
}
menifestfile
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
public static String getSoapResponse(String postFixOfUrl) {
try {
if (General.AppContext != null
&& General.isOnline(General.AppContext)) {
HttpGet httpget = new HttpGet(BaseURL + postFixOfUrl);
Log.i("SOAP", "URI:" + BaseURL + postFixOfUrl);
httpget.setHeader("Content-Type",
"application/json;charset=utf-8");
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httpget);
HttpEntity r_entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_entity);
return xmlString.toString();
} else {
// return
// "[{\"erorr\":{\"no_internet\":\"No internet connection\"}}]";
if (General.AppActivity != null) {
General.AppActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
General.AppContext,
General.AppContext
.getResources()
.getString(
R.string.no_internet_connection),
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
} catch (Exception e) {
HandleException.catchException(e, true);
}
return null;
}
// post method
public static String getSoapResponseByPost(String postFixOfUrl,
ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
try {
if (General.AppContext != null
&& General.isOnline(General.AppContext)) {
HttpPost httppost = new HttpPost(BaseURL + postFixOfUrl);
Log.i("SOAP", "URI:" + BaseURL + postFixOfUrl);
// httppost.setHeader("Content-Type",
// "text/html;charset=utf-8");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httppost);
HttpEntity r_entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_entity);
return xmlString.toString();
} else {
// return
// "[{\"erorr\":{\"no_internet\":\"No internet connection\"}}]";
if (General.AppActivity != null) {
General.AppActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
General.AppContext,
General.AppContext
.getResources()
.getString(
R.string.no_internet_connection),
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
} catch (Exception e) {
HandleException.catchException(e, true);
}
return null;
}
public static String getSoapResponseForImage(String postFixOfUrl,
List<NameValuePair> nameValuePairs,
List<NameValuePair> filenameValuePairs) {
String xmlString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
try {
MultipartEntity entity = new MultipartEntity();
for (int index = 0; index < filenameValuePairs.size(); index++) {
File myFile = new File(filenameValuePairs.get(index).getValue());
if (myFile.exists()) {
FileBody fileBody = new FileBody(myFile);
entity.addPart(filenameValuePairs.get(index).getName(),
fileBody);
}
}
for (int index = 0; index < nameValuePairs.size(); index++) {
entity.addPart(nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue(),
Charset.forName("UTF-8")));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity r_entity = response.getEntity();
xmlString = EntityUtils.toString(r_entity);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("SOAP ", "Result : " + xmlString.toString());
return xmlString.toString();
}
public class ParsedResponse {
public Object o;
public boolean error = false;
}
public class General {
public static Context AppContext = null;
public static Activity AppActivity = null;
public static boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}}
public class BaseActivity extends Activity {
protected SharedPreferences prefs;
public ProgressDialog progressDialog;
General.AppContext = getApplicationContext();
General.AppActivity = BaseActivity.this;
prefs = PreferenceManager.getDefaultSharedPreferences(this);}
public class ErrorMgmt {
private Boolean error;
private String errorMessage;
private String exceptionMessage;
public ErrorMgmt(String exceptionMessage) {
error = false;
errorMessage = "";
this.exceptionMessage = exceptionMessage;
}
public ErrorMgmt() {
error = false;
errorMessage = "";
exceptionMessage = "";
}
public String getErrorMessage() {
if (error) {
if (errorMessage.equals("")) {
return exceptionMessage;
} else {
return errorMessage;
}
}
return null;
}
#SuppressWarnings("rawtypes")
public Boolean strError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONObject objJson = new JSONObject(JsonResponse);
String strJson = objJson.getString("JsonResponse");
if(!strJson.equals("Please enter valid email")) {
this.error = true ;
errorMessage = "";
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
#SuppressWarnings("rawtypes")
public Boolean isObjError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONObject objJson = new JSONObject(JsonResponse);
if (objJson != null && !objJson.isNull("error") ) {
this.error = true;
Iterator IError = objJson.keys();
errorMessage = "";
while (IError.hasNext()) {
String key = (String) IError.next();
errorMessage += objJson.getString(key) + "\n";
}
} else if (objJson != null && !objJson.isNull("statusCode")) {
Integer statusCode = objJson.getInt("statusCode");
if (statusCode > 200) {
this.error = true;
} else {
this.error = false;
}
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
#SuppressWarnings("rawtypes")
public Boolean isError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONArray arrJson = new JSONArray(JsonResponse);
if (!arrJson.isNull(0) && !arrJson.getJSONObject(0).isNull("erorr")) {
this.error = true;
JSONObject objError = arrJson.getJSONObject(0);
Iterator IError = objError.keys();
errorMessage = "";
while (IError.hasNext()) {
String key = (String) IError.next();
errorMessage += objError.getString(key) + "\n";
}
} else if (!arrJson.isNull(0)
&& !arrJson.getJSONObject(0).isNull("statusCode")) {
Integer statusCode = arrJson.getJSONObject(0).getInt(
"statusCode");
if (statusCode > 200) {
this.error = true;
} else {
this.error = false;
}
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
public void SetForsedError(Boolean val) {
error = true;
}
}
// Api for register with Email
public static ParsedResponse apiRegister(String name, String email,
String password) throws Exception {
ArrayList<NameValuePair> alNameValuePairs = new ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("name", name);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("email", email);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("password", password);
alNameValuePairs.add(nameValuePair);
// nameValuePair = new BasicNameValuePair("fb_uid", "");
// alNameValuePairs.add(nameValuePair);
String result = Soap.getSoapResponseByPost("user/register",
alNameValuePairs);
Log.e("apiRegister", result);
ErrorMgmt errMgmt = new ErrorMgmt(General.AppContext.getResources()
.getString(R.string.error_loading_data));
ParsedResponse p = new ParsedResponse();
p.error = false;
if (result != null && !result.equals("")) {
JSONObject jObject = new JSONObject(result);
String code = "";
if (!jObject.isNull("statusCode")) {
code = jObject.getString("statusCode");
}
if (code.equals("200")) {
JSONArray jsonArray = jObject.getJSONArray("User");
if (jsonArray.length() > 0) {
ArrayList<UserData> arrayList = new ArrayList<UserData>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
UserData objUserData = new UserData();
if (!jsonObject.isNull("uid")) {
objUserData.uid = jsonObject.getString("uid");
}
if (!jsonObject.isNull("name")) {
objUserData.name = jsonObject.getString("name");
}
if (!jsonObject.isNull("email")) {
objUserData.email = jsonObject.getString("email");
}
if (!jsonObject.isNull("password")) {
objUserData.password = jsonObject
.getString("password");
}
if (!jsonObject.isNull("created_date")) {
objUserData.created_date = jsonObject
.getString("created_date");
}
if (!jsonObject.isNull("status")) {
objUserData.status = jsonObject.getString("status");
}
if (!jsonObject.isNull("fb_uid")) {
objUserData.fb_uid = jsonObject.getString("fb_uid");
}
if (!jsonObject.isNull("account_type")) {
objUserData.account_type = jsonObject
.getString("account_type");
}
if (!jsonObject.isNull("profile_img")) {
objUserData.profile_img = jsonObject
.getString("profile_img");
}
if (!jsonObject.isNull("birthdate")) {
objUserData.birthdate = jsonObject
.getString("birthdate");
}
if (!jsonObject.isNull("city")) {
objUserData.city = jsonObject.getString("city");
}
JSONArray jsonArray2 = jsonObject
.getJSONArray("usersubscribe");
if (jsonArray2.length() > 0) {
for (int i1 = 0; i1 < jsonArray2.length(); i1++) {
JSONObject jsonObject2 = jsonArray2
.getJSONObject(i1);
if (!jsonObject2.isNull("isSubscribe")) {
objUserData.isSubscribe = jsonObject2
.getString("isSubscribe");
}
if (!jsonObject2.isNull("amount")) {
objUserData.amount = jsonObject2
.getString("amount");
}
}
}
arrayList.add(objUserData);
p.o = arrayList;
}
} else {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.err_norecords));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
}
if (code.equals("401")) {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.allready_regi));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
} else {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.err_norecords));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
return p;
}
// Login with Facebook
private class GetFacebookLogin extends AsyncTask<Void, Void, Void> {
private ParsedResponse p = null;
private String message = "";
private Boolean error = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
p = new ParsedResponse();
p = Soap.apiUserLoginFacebook(fbID);
if (p.error) {
ErrorMgmt errmgmt = (ErrorMgmt) p.o;
message = errmgmt.getErrorMessage();
error = true;
} else {
arrayList.clear();
arrayList.addAll((ArrayList<UserData>) p.o);
error = false;
}
} catch (Exception e) {
message = "problem in loading data";
error = true;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
if (error) {
new AlertDialog.Builder(Register_Login_Screen.this)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
} else {
UserData objUserData = new UserData();
for (int i = 0; i < arrayList.size(); i++) {
objUserData = arrayList.get(i);
}
String profileImage = "";
try {
URL image_value = new URL("http://graph.facebook.com/"
+ fbID + "/picture?height=150&width=150");
profileImage = String.valueOf(image_value);
Log.e("fb_image_path", "" + image_value);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Editor e = prefs.edit();
e.putBoolean(General.PREFS_login, true);
e.putString(General.PREFS_Uid, objUserData.uid);
e.putString(General.PREFS_name, objUserData.name);
e.putString(General.PREFS_email, objUserData.email);
e.putString(General.PREFS_fb_uid, objUserData.fb_uid);
e.putString(General.PREFS_logintype, General.PREFS_valuefblogin);
if (objUserData.profile_img != null
&& !objUserData.profile_img.equals("")) {
e.putString(General.PREFS_profile_img,
objUserData.profile_img);
} else {
e.putString(General.PREFS_profile_img, profileImage);
}
e.putString(General.PREFS_account_type,
objUserData.account_type);
e.putString(General.PREFS_birthdate, objUserData.birthdate);
e.putString(General.PREFS_city, objUserData.city);
e.putString(General.PREFS_subscribed, objUserData.isSubscribe);
e.putString(General.PREFS_amount, objUserData.amount);
String[] strings = null;
for (int i = 0; i < objUserData.screenerArr.size(); i++) {
String queString = objUserData.screenerArr.get(i);
strings = queString.split(",");
String question1 = strings[0];
e.putString("RosaRosa_screener_question" + (i + 1),
question1);
e.putBoolean("RosaRosa_screener_ans" + (i + 1), true);
String ans1 = strings[1];
e.putString(
"RosaRosa_screener_question" + (i + 1) + "_ans",
ans1);
Log.e("question", "" + question1 + ans1);
}
e.commit();
Toast.makeText(Register_Login_Screen.this, R.string.succ_login,
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register_Login_Screen.this,
Personal_Stylist_Activity.class);
startActivity(intent);
finish();
}
}
}

Categories

Resources