JSON parsing android

半腔热情 提交于 2019-12-06 07:41:13

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();
            }
        }

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!