Agregue TextView programáticamente con json

Trato de agregar TextView en mi LinearLayout. But it's a little complicated because i need to create all the app programmatically and add element programmatically. I parse a json file and i get View from him like this :

JSONParser.java :

public class JSONParser extends Activity {

 private JSONObject myjsonobj = null;
    //  Map<String, String> jsonresult = new HashMap<String, String>();

// private JSONArray myinterface = null;

    public JSONParser(String file) throws IOException {
        file = "assets/JsonTest.txt";

        InputStream is = this.getClass().getClassLoader().getResourceAsStream(file);
        StringBuffer sb = new StringBuffer();
        try {
            BufferedReader buf = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            String temp;
            while ((temp = buf.readLine()) != null)
                sb.append(temp);
        } catch (IOException e) {
            e.printStackTrace();
        } finally { }

        try {
            Log.e("Parser JSON", "Parser JSON OK");
            myjsonobj = new JSONObject(sb.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("OBJSON", myjsonobj.toString());
    }

    public ClassicView getClassicViewWithId(int id, Context context) throws JSONException {
         JSONArray myView = myjsonobj.getJSONObject("interface").getJSONArray("View");                  
        for (int i = 0; i < myView.length(); i++) {
            if (myView.getJSONObject(i).getInt("id") == id) {
                Log.e("IDVIEW", myView.getJSONObject(i).getString("id"));
                ClassicView myClassicView = new ClassicView(myView.getJSONObject(i).getInt("id"));

                classicSetLabel(myView.getJSONObject(i).getJSONArray("Label"), myClassicView, context);
                return myClassicView;
            }
        }
        return null;
    }

ClassicView.java :

public class ClassicView extends Activity {

public int myid;


public ClassicView() {

}
     public ClassicView(int id){
         super();
         myid = id;
     }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.linearlayout);

        LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout2);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( new ViewGroup.MarginLayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));           
        setContentView(ll);
    }
}

I have my function SetClassicLabel en mi JSONParser class. I want to add undefined number of TextView. I read the number in my json file. I want to add TextView en mi ClassicView but I don't know how to do this. I tried this but it doesn't work :

public RelativeLayout.LayoutParams setPosition(int positionX,int positionY){


        RelativeLayout.LayoutParams params = 
                  new RelativeLayout.LayoutParams(
                      RelativeLayout.LayoutParams.WRAP_CONTENT, 
                      RelativeLayout.LayoutParams.WRAP_CONTENT);

        params.addRule(positionX);
        params.addRule(positionY);
        return params;
    }

    public void classicSetLabel(JSONArray myArrayLabel, ClassicView classicView, Context context) throws JSONException {

        Log.e("@@@@@WARNING TEXTLABEL :", "classicSetLabelErreur1");
        Log.e("@@@@@WARNING TEXTLABEL :", "classicSetLabelErreur2");
        for (int i = 0; i < myArrayLabel.length(); i++) {
            Log.e("CLASSICVIEW", classicView.toString());
            TextView myTextView = new TextView(context);
            LinearLayout myLayout = new LinearLayout(context);
            myTextView.append(myArrayLabel.getJSONObject(i).getString("text"));
            myLayout.addView(myTextView, setPosition(RelativeLayout.CENTER_HORIZONTAL,RelativeLayout.CENTER_VERTICAL));
            Log.e("@@@@@WARNING TEXTLABEL :", myArrayLabel.getJSONObject(i).getString("text"));
            Log.e("@@@@@WARNING TEXTPOS_X", myArrayLabel.getJSONObject(i).getString("position_x"));
            Log.e("@@@@@WARNING TEXTPOS_Y", myArrayLabel.getJSONObject(i).getString("position_y"));
            setContentView(myLayout);
        }

}

MainActivity.java :

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    JSONParser jParser = null;
    try {
        jParser = new JSONParser("JsonTest.txt");
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        ClassicView view = jParser.getClassicViewWithId(0, MainActivity.this);
        //Log.e("idVIEWMAIN :", msg)
        Intent intent = new Intent(MainActivity.this, view.getClass());
        startActivity(intent);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Aquí está mi Logcat :

  11-27 06:34:50.878: E/IDVIEW(30402): 0
  11-27 06:34:50.878: E/@@@@@WARNING TEXTLABEL :(30402): classicSetLabelErreur1
 11-27 06:34:50.888: E/@@@@@WARNING TEXTLABEL :(30402): classicSetLabelErreur2
 11-27 06:34:50.888: E/CLASSICVIEW(30402): com.fchps.bya.classicview.ClassicView@41bdee80
 11-27 06:34:50.898: E/@@@@@WARNING TEXTLABEL :(30402): bonjour comment ca va ?
 11-27 06:34:50.898: E/@@@@@WARNING TEXTPOS_X(30402): 200
 11-27 06:34:50.898: E/@@@@@WARNING TEXTPOS_Y(30402): 400
 11-27 06:34:50.898: D/AndroidRuntime(30402): Shutting down VM
 11-27 06:34:50.898: W/dalvikvm(30402): threadid=1: thread exiting with uncaught exception   (group=0x411d32a0)
 11-27 06:34:50.898: E/AndroidRuntime(30402): FATAL EXCEPTION: main
 11-27 06:34:50.898: E/AndroidRuntime(30402): java.lang.RuntimeException: Unable to start  activity ComponentInfo{com.fchps.bya/com.fchps.bya.MainActivity}:   java.lang.NullPointerException
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2081)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2106)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  android.app.ActivityThread.access$700(ActivityThread.java:134)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1217)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at   android.os.Handler.dispatchMessage(Handler.java:99)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at android.os.Looper.loop(Looper.java:137)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  android.app.ActivityThread.main(ActivityThread.java:4856)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  java.lang.reflect.Method.invokeNative(Native Method)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  java.lang.reflect.Method.invoke(Method.java:511)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at dalvik.system.NativeStart.main(Native  Method)
 11-27 06:34:50.898: E/AndroidRuntime(30402): Caused by: java.lang.NullPointerException
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  android.app.Activity.setContentView(Activity.java:1921)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  com.fchps.bya.json.JSONParser.classicSetLabel(JSONParser.java:107)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at  com.fchps.bya.json.JSONParser.getClassicViewWithId(JSONParser.java:71)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at com.fchps.bya.MainActivity.onCreate(MainActivity.java:32)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at android.app.Activity.performCreate(Activity.java:5047)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2045)
 11-27 06:34:50.898: E/AndroidRuntime(30402):   ... 11 more

Somebody understand what I want to do and can explain to me what I make wrong please ?

Gracias :)

preguntado el 27 de noviembre de 13 a las 05:11

There is issue in your MainActivity onCreate method. Please post some code of your MainActivity. -

1 Respuestas

Can you please try like this:

LinearLayout layout = ... // Your linear layout.
ListAdapter adapter = ... // Your adapter. Add the JSON text in the list-adapter
                          //( populate the adapter using you json parser)
for (int i = 0; i < adapter.getCount(); i++) {
  View item = adapter.getView(i, null, null);
  layout.addView(item);
}

respondido 27 nov., 13:06

I don't understand :/ - Fcps

Are you looking for updating the listView with dynamic textView? - Pradip

No I want to set TextView in my layout. If I have 5 TextView in my json. I need to generate 5 TextView in Layout. Not a ListView but it's hard. - Fcps

no need to define textView in LayOut. Define LinearLayout in your Layout.xml. Now from youActivity class. Get the Json data and put it in ListAdapter and iterate over it to add new textView to your LinearLayout. have you got my point. - Pradip

I don't want to create Layout.xml . I want to put my TextView in my ClassicView class. There is a Layout in ClassicView class. My ClassicView is generated with json and it worked. I want to do the same but for an X number of textview. - Fcps

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.