简体   繁体   中英

Display json data in android?

i am trying to display json content in an android application but it is not reading it . i want it to get the "statusmessage" in the json file on the first page and sent it to the next page and display using sharedpefrences. but it is returning "anon" as the value instead of "Hi +2348055550055, an ACCESS FEE of N20.00 will be charged in order to access this Platform". in the dialog in mainactivity.java. i have no error message it is no just returning the value.

this is the json file

{headers: 
[{
id: "4",
name: "GLO",
code: "GLO",
status: "Inactive",
statusMessage: "Hi +2348055550055, an ACCESS FEE of N20.00 will be charged in order to access this Platform"
}]
}

this is my main java class

package com.mall.first;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ActivitySplash extends Activity {
    private ProgressDialog pDialog;
    int flag=0;

    JSONParser jsonParser = new JSONParser();
    private static final String api = "http://10.0.2.2/angl/com.php";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.splash);
       ImageView image =    (ImageView)findViewById(R.id.image1);

        Picasso.with(getBaseContext()).load("http://api.dobox.tv/img/gloSplashScreen.png").into(image);

        new CountDownTimer(5000,1000) {

            @Override
            public void onFinish() {
          new loginAccess().execute();
                Intent intent = new Intent(getBaseContext(), MainActivity.class);

                startActivity(intent);

                finish();

            }
            @Override
            public void onTick(long millisUntilFinished) {

            }
        }.start();

    }

    class loginAccess extends AsyncTask<String, String, Boolean> {

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ActivitySplash.this);
            pDialog.setMessage("Login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected Boolean doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;


            try {

                List<NameValuePair> params = new ArrayList<NameValuePair>();


                Log.d("request!", "starting");

                JSONObject json = jsonParser.getJSONFromUrl(api);
                // check your log for json response
                Log.d("Login attempt", json.toString());

                JSONArray categories = json.getJSONArray("headers");

                for (int i = 0; i < categories.length(); i++) {
                    String state = categories.getJSONObject(i).getString("state");
                    String status = categories.getJSONObject(i).getString("status");

                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(ActivitySplash.this);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("state", state);

                    edit.putString("status", status);

                    edit.commit();


                    // Close all views
                }
            }catch (Throwable e){
                e.printStackTrace();
            }
            return true;
        }
        protected void onPostExecute(Boolean file_url) {
            pDialog.dismiss();
            if(flag==1)
                Toast.makeText(ActivitySplash.this,"Please Enter Correct informations", Toast.LENGTH_LONG).show();

        }

    }
}

this is my second class

package com.mall.first;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends SherlockFragmentActivity {


    DrawerLayout mDrawerLayout;
    ListView mDrawerList;
    ActionBarDrawerToggle mDrawerToggle;
    MenuListAdapter mMenuAdapter;
    String[] titl;
    Button pend;
    int[] icon;
    String pic;
    Fragment menus = new Menus();

        TextView mystatu,myuser,nick,status;

        public static final String PREFS_NAME = "LoginPrefs";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer_main);
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        status = sp.getString("status", "anon");

        root();

}



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {

            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        mDrawerToggle.onConfigurationChanged(newConfig);
    }
    public void root(){
        LayoutInflater li = LayoutInflater.from(MainActivity.this);
        View promptsView = li.inflate(R.layout.prompts, null);

        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                MainActivity.this);

        alertDialogBuilder.setView(promptsView);




        alertDialogBuilder
                .setCancelable(false)
                .setMessage(status)
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int id) {

                                Toast.makeText(MainActivity.this, "payment has been done", Toast.LENGTH_SHORT).show();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int id) {

                                System.exit(0);
                            }
                        });


        AlertDialog alertDialog = alertDialogBuilder.create();

        alertDialog.show();
    }

}

The code inside CountDownTimer->OnFinish is wrong because you open the intent before finishing the asynctask. You should move the intent to the OnPostExecute method of your asynctask. That way, you ensure that status is written on the sharedPreferences before opening the MainActivity.

new CountDownTimer(5000,1000) {

         @Override
         public void onFinish() {
            new loginAccess().execute();

            //===========================================================
            //Move the following 3 lines to OnPostExecute
            //===========================================================
            Intent intent = new Intent(getBaseContext(), MainActivity.class);
            startActivity(intent);
            finish();

        }
        @Override
        public void onTick(long millisUntilFinished) {

        }
    }.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM