2017-06-29 53 views
0

我試圖在Android代碼中打印json回顯的方法;但不只是一個簡單的回聲,而是一個admob代碼;讓AdMob廣告單元將在服務器JSON文件和我叫它爲Android的代碼如下:JSON文件是如下:在Android應用上打印PHP Echo

{ 
"ads":{  
    "inter":"ca-app-pub-3940256099942544/1033173712" 
} 
} 

是否有可能做到這一點?所以我可以從服務器中的文件更改admob代碼,而無需更新商店中的應用程序? 如果是這樣的話,android代碼將負責將該字符串提取到應用程序中。

我的代碼是這樣的:

public class MainActivity extends AppCompatActivity { 
private RecyclerView mRecyclerView; 
private RecyclerView.LayoutManager mLayoutManager; 

private List<Song> songList; 
private SongAdapter songAdapter; 

// URL of object to be parsed 
String JsonURL = "http://xxxxx.com/ads.json"; 
// This string will hold the results 
String data = ""; 
RequestQueue requestQueue; 
//TODO: full screen ad 
private InterstitialAd mInterstitialAd; 
//TODO: selected item 
private int mPosition; 

String[] names = {"test1", "test2", "test3", "test4", "test5", "test6"}; 

String[] singers = {"test1", "test2", "test3", "test4", "test5", "test6"}; 

int[] pics = { 
     R.drawable.tip1, 
     R.drawable.tip1, 
     R.drawable.tip1, 
     R.drawable.tip1, 
     R.drawable.tip1, 
     R.drawable.tip1}; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); 
    setupActionBar(); 

    requestQueue = Volley.newRequestQueue(this); 
    JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL, 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 
        try { 
         JSONObject obj = response.getJSONObject("ads"); 

         String Inter = obj.getString("inter"); 
         data = Inter; 

        } 
        catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        Log.e("Volley", "Error"); 
       } 
      } 
    ); 
    requestQueue.add(obreq); 

    //Use this setting to improve performance if you know that changes in 
    //the content do not change the layout size of the RecyclerView 
    if (mRecyclerView != null) { 
     mRecyclerView.setHasFixedSize(true); 
    } 

    //using a linear layout manager 
    mLayoutManager = new LinearLayoutManager(this); 

    //use this in case of gridlayoutmanager 
    //mLayoutManager = new GridLayoutManager(this,2); 

    //use this in case of Staggered GridLayoutManager 
    //mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); 


    mRecyclerView.setLayoutManager(mLayoutManager); 

    //intializing an arraylist called songlist 
    songList = new ArrayList<>(); 

    //adding data from arrays to songlist 
    for (int i = 0; i < names.length; i++) { 
     Song song = new Song(names[i], singers[i], i + 1, pics[i]); 
     songList.add(song); 
    } 
    //initializing adapter 
    songAdapter = new SongAdapter(songList); 

    //specifying an adapter to access data, create views and replace the content 
    mRecyclerView.setAdapter(songAdapter); 
    songAdapter.notifyDataSetChanged(); 

    mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() { 

     @Override 
     public void onItemClick(View view, int position) { 
      // TODO: check condition it should whether show ad or not 
      Integer[] adPositions = {1,2}; // list of ad positions 

      if (!Arrays.asList(adPositions).contains(position)) { 
       goToItem(position); 
       return; 
      } 

      // TODO: check ad is loaded before showing 
      if (mInterstitialAd.isLoaded()) { 
       mPosition = position; 
       mInterstitialAd.show(); 
      } else { 
       goToItem(position); 
      } 
     } 
    })); 


    // TODO:init ad 
    mInterstitialAd = new InterstitialAd(this); 
    mInterstitialAd.setAdUnitId(data); 
    mInterstitialAd.setAdListener(new AdListener() { 
     @Override 
     public void onAdClosed() { 
      requestNewInterstitial(); 
      goToItem(mPosition); 
     } 
    }); 

    //TODO: load new ad 
    requestNewInterstitial(); 
} 

//TODO: load new ad 
private void requestNewInterstitial() { 
    AdRequest adRequest = new AdRequest.Builder() 
      .build(); 
    mInterstitialAd.loadAd(adRequest); 
} 

//TODO: open item at position 
private void goToItem(int position) { 
    switch (position) { 
     case 0: 
      startActivity(new Intent(MainActivity.this, Test1Activity.class)); 
      break; 
     case 1: 
      startActivity(new Intent(MainActivity.this, Test2Activity.class)); 
      break; 
     case 2: 
      startActivity(new Intent(MainActivity.this, Test3Activity.class)); 
      break; 
     case 3: 
      startActivity(new Intent(MainActivity.this, Test4Activity.class)); 
      break; 
     case 4: 
      startActivity(new Intent(MainActivity.this, Test5Activity.class)); 
      break; 
     case 5: 
      startActivity(new Intent(MainActivity.this, Test6Activity.class)); 
      break; 
     default: 
      break; 
    } 
} 

private void setupActionBar() { 
    ActionBar actionBar = getSupportActionBar(); 
    if (actionBar != null) { 
     // Show the Up button in the action bar. 
     actionBar.setDisplayHomeAsUpEnabled(true); 
    } 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 
    if (id == android.R.id.home) { 
     finish(); 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 



} 

編輯

的代碼工作正常,除了一件事是應用程序崩潰(有時)當我點擊打開要展示活動插入到項目之前的插頁式代碼。我不希望應用程序崩潰了。

我認爲有時無法連接到服務器多數民衆贊成爲什麼它崩潰(這隻在間隙)nativeExpress總是罰款連接與否。

我不希望應用程序崩潰了,有無論如何驗證連接到服務器,或強制它首先連接到服務器,如果成功>加載>顯示 如果不連接到服務器只是忽略並轉到項目。

+0

漂亮stamdard調用Android中的代碼PHP腳本,並閱讀其回聲。有什麼問題? – greenapps

+0

謝謝你回答,問題是我沒有關於如何做到這一點的知識,我在這裏試過這種方式,但無法弄清楚它https://stackoverflow.com/questions/22177821/how-doi-i-打印php-echo-on-my-android-app,你能幫我一個代碼嗎 – user2972389

回答

0

echo在PHP中通過HTTP(S)連接向客戶端發送文本。

所以,據我所知,你想從你的服務器檢索admob id來顯示使用特定id值的admob橫幅。

檢索一些數據,你可以使用任何你想要的庫。

例如,排LIB https://developer.android.com/training/volley/simple.html

final TextView mTextView = (TextView) findViewById(R.id.text); 
... 

// Instantiate the RequestQueue. 
RequestQueue queue = Volley.newRequestQueue(this); 
String url ="http://www.google.com"; 

// Request a string response from the provided URL. 
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
      new Response.Listener<String>() { 
    @Override 
    public void onResponse(String response) { 
     // Display the first 500 characters of the response string. 
     mTextView.setText("Response is: "+ response.substring(0,500)); 
    } 
}, new Response.ErrorListener() { 
    @Override 
    public void onErrorResponse(VolleyError error) { 
     mTextView.setText("That didn't work!"); 
    } 
}); 
// Add the request to the RequestQueue. 
queue.add(stringRequest); 

,或者JSOUP庫https://jsoup.org/download

`compile 'org.jsoup:jsoup:1.10.2'` 

用法

Document doc = Jsoup.connect(URL).get();

EDIT

我想說,只有在檢索data變量(即admob鍵)後,您才必須初始化插頁式廣告。

我現在的代碼,你試圖在檢索到回調之前,嘗試inialize interstital。

我能建議什麼?

在成功回調中移動初始化。

即,

@Override 
       public void onResponse(JSONObject response) { 
        try { 
         JSONObject obj = response.getJSONObject("ads"); 

         String Inter = obj.getString("inter"); 
         data = Inter; 
//HERE YOU NEW CODE 

mInterstitialAd = new InterstitialAd(this); 
mInterstitialAd.setAdUnitId(data); 
mInterstitialAd.setAdListener(new AdListener() { 
    @Override 
    public void onAdClosed() { 
     requestNewInterstitial(); 
     goToItem(mPosition); 
    } 
}); 

requestNewInterstitial(); 

// NEW CODE } 趕上(JSONException E){e.printStackTrace 結束(); }}

不要忘了,從以前的位置刪除此注射;)

+0

我跟着這裏的教程https://www.thorntech.com/2016/03/parsing-json-android-using-排除庫/不使用textview方法,但只是給調用admob id並給它一個變量,然後在admob代碼中使用該變量,但沒有奏效。但是當我把代碼直接放在持有人數據=「xxxxx」的時候,所以它看起來像代碼不能解析持有人data =「」中的admob id,請你幫忙請 – user2972389

+0

@ user2972389請發表你的android代碼和http服務器響應。 – Vyacheslav

+0

Part1: String JsonURL =「http://xxxxxx.com/ads.json」; //此字符串將保存結果 String data =「」; RequestQueue requestQueue; – user2972389